Spring Boot错误控制器检索原始请求

时间:2019-02-20 23:30:07

标签: java spring spring-boot

默认情况下,Spring Boot将/error映射到BasicErrorController。我想记录异常以及导致异常的请求。如何在BasicErrorController或新的CustomErrorController中获得原始请求。看起来,当引发异常并且原始请求信息消失或无法将错误与原始请求映射时,Spring Boot将向/error发出新请求。 enter image description here

5 个答案:

答案 0 :(得分:1)

如果您使用控制器建议来处理异常,则具有@ExceptionHandler的方法可以将请求作为参数注入,例如:

@ControllerAdvice
public class YourExceptionHandler
{
    @ExceptionHandler
    public ResponseEntity handleExceptions(HttpServletRequest request, Exception exception)
    {
        // use request to populate error object with details like requestId
        LOGGER.debug(String.valueOf(request));
        LOGGER.error(exception.getMessage(), exception);
     }
}

答案 1 :(得分:1)

获取:

String url = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);

答案 2 :(得分:0)

为避免任何误导性信息,Spring Boot 不会/error端点发出新请求。而是将异常包装在原始请求中,并将其转发到/error端点。如果您未提供自定义错误处理程序,则请求将由BasicErrorHandler处理。

在这种情况下,如果您使用的是interceptor,则拦截器将被两次调用-一个用于原始请求,另一个用于转发的请求。

要检索原始请求信息,请查看转发的请求的属性。基本上,您可以从这些属性javax.servlet.error.message, javax.servlet.error.status_code, org.springframework.web.servlet.DispatcherServlet.EXCEPTION中获取错误消息。

以下是与Spring Boot中的错误处理相关的一些资源:

答案 3 :(得分:0)

这是一个工作示例:

@RestController
public class MyErrorController implements ErrorController {

    private static final Logger LOG = LoggerFactory.getLogger(MyErrorController.class);

    private static final String PATH = "/error";

    private final ErrorAttributes errorAttributes;

    public MyErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping(value = PATH)
    public ErrorDTO error(WebRequest webRequest, HttpServletRequest httpServletRequest) {

        // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring.
        Map<String, Object> attrs = errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());

        LOG.warn("Forwarded Error Request: {} ", attrs.get("path"), (Throwable)
                httpServletRequest.getAttribute("javax.servlet.error.exception"));

        ErrorDTO dto = new ErrorDTO();
        dto.message = (String) attrs.get("error");
        dto.path = (String) attrs.get("path");
        dto.timestamp = attrs.get("timestamp").toString();
        return dto;
    }
 }

答案 4 :(得分:0)

@Override
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException exception,
        HttpHeaders headers,
        HttpStatus status,
        WebRequest request) {
    OriginalRequestObject originalRequest = (OriginalRequestObject) exception.getBindingResult().getTarget();
    ErrorResponse errorResponse = new ErrorResponse(
            status.value(),
            originalRequest.getId() + " " + exception.getMessage());
    return ResponseEntity.status(status).body(myErrorResponse);
}