在 spring 引导中提供通用异常处理程序,将所有异常转换为 HTTP 500

Providing Generic Exception handler in spring boot convetring all exception into HTTP 500

在我的应用程序中,我已经为特定异常和一般异常 (Exception.class) 提供了处理程序。问题是每当向 API 提供错误输入时,它都会抛出 BAD REQUEST(HTTP-400)。但是,如果出现 BAD 请求,它会返回 HTTP-500。验证 spring 启动会自动触发自身,但会被 handleApplicationException 捕获。

@ExceptionHandler(value = Exception.class)
public ResponseEntity<ErrorResponseDTO> handleApplicationException(final Exception ex) {
    LOGGER.error("Unhandled Exception occurred ", ex);

    ErrorResponseDTO errorResponseDTO = new ErrorResponseDTO();
    errorResponseDTO.setMessage("Internal Server Error");
    errorResponseDTO.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);

    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponseDTO);
}

@ExceptionHandler(value = ResourceNotFoundException.class)
public ResponseEntity<ErrorResponseDTO> handleResourceNotFoundException(final ResourceNotFoundException
    notFoundException) {

    LOGGER.error("Handling resource not found exception", notFoundException);
    ErrorResponseDTO errorResponseDTO = new ErrorResponseDTO();
    errorResponseDTO.setMessage(notFoundException.getMessage());
    errorResponseDTO.setHttpStatus(HttpStatus.NOT_FOUND);

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponseDTO);
}

我认为为 Exception class 提供异常处理程序是一种不好的做法。大多数 exceptions 通常继承自 Exception class 并反过来被您的 handleApplicationException 处理程序捕获。

Focus on handling specific exceptions.

例如,如果客户端发送格式错误的 JSON 并抛出 HttpMessageNotReadableException,您可以在 Exception Handler 中捕获它并执行操作你想要它,或者简单地删除 Exception.class Spring 的 Exception Handler 将 return 一个 400 - BAD REQUEST 响应。