Skip to content

Commit

Permalink
Include error in the request when using ProblemDetail API
Browse files Browse the repository at this point in the history
This is a workaround for missing log correlation
(see details in spring-projects/spring-framework#29398).
  • Loading branch information
alexandreroman committed Feb 3, 2023
1 parent 2020639 commit 6ca1b0a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
Expand Up @@ -18,6 +18,7 @@

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
Expand All @@ -33,6 +34,8 @@
import java.util.Map;
import java.util.Random;

import static org.springframework.web.util.WebUtils.ERROR_EXCEPTION_ATTRIBUTE;

@SpringBootApplication
public class Application {
public static void main(String[] args) {
Expand Down Expand Up @@ -115,11 +118,12 @@ public String getItemId() {
@RestControllerAdvice
class ItemControllerAdvice {
@ExceptionHandler(ItemNotFoundException.class)
ProblemDetail handleItemNotFoundException(ItemNotFoundException e) {
ProblemDetail handleItemNotFoundException(HttpServletRequest request, ItemNotFoundException e) {
// Map this exception to a RFC 7807 entity (Problem Details for HTTP APIs).
final var detail = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
detail.setTitle(e.getMessage());
detail.setType(URI.create("urn:problem-type:item-not-found"));
request.setAttribute(ERROR_EXCEPTION_ATTRIBUTE, e);
return detail;
}
}
Expand Down
Expand Up @@ -18,6 +18,7 @@

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
Expand All @@ -35,6 +36,8 @@
import java.util.Map;
import java.util.Random;

import static org.springframework.web.util.WebUtils.ERROR_EXCEPTION_ATTRIBUTE;

enum OrderState {
Draft, New, InProgress, OnHold, Completed, Canceled
}
Expand Down Expand Up @@ -122,11 +125,12 @@ public String getOrderId() {
@RestControllerAdvice
class OrderControllerAdvice {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleOrderNotFoundException(OrderNotFoundException e) {
ProblemDetail handleOrderNotFoundException(HttpServletRequest request, OrderNotFoundException e) {
// Map this exception to a RFC 7807 entity (Problem Details for HTTP APIs).
final var detail = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
detail.setTitle(e.getMessage());
detail.setType(URI.create("urn:problem-type:order-not-found"));
request.setAttribute(ERROR_EXCEPTION_ATTRIBUTE, e);
return detail;
}
}
Expand Down

0 comments on commit 6ca1b0a

Please sign in to comment.