如何使用 ExceptionHandler 在 Spring Boot Rest 中包装 Path Not Found 异常?

How to wrap Path Not Found Exception in Spring Boot Rest using ExceptionHandler?

我正在使用 Spring Boot 和 Spring Rest 示例。在此示例中,我传递自定义 header,如果该值有效,则端点被成功调用,如果自定义 header 值不正确,那么我得到以下响应,我想将其包装到显示中使用 @ControllerAdvice ExceptionHandler.

给最终用户

注意:我经历了 Spring mvc - How to map all wrong request mapping to a single method,但在我的例子中,我根据 CustomHeader 做出决定。

{
    "timestamp": "2020-01-28T13:47:16.201+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/employee-data/employee-codes"
}

控制器

@Operation(summary = "Find Employee")
@ApiResponses(value = { @ApiResponse(code = 200, message = "SUCCESS"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
@Parameter(in = ParameterIn.HEADER, description = "X-Accept-Version", name = "X-Accept-Version", 
        content = @Content(schema = @Schema(type = "string", defaultValue = "v1", 
        allowableValues = {HeaderConst.V1}, implementation = Country.class)))
@GetMapping(value = "/employees/employee-codes", headers = "X-Accept-Version=v1")
public ResponseEntity<Employees> findEmployees(
        @RequestParam(required = false) String employeeCd,
        @RequestParam(required = false) String firstName,
        @RequestParam(required = false) Integer lastName) {
    Employees response = employeeService.getEmployees(employeeCd, firstName, lastName);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

我已经实现了 HttpMessageNotReadableExceptionHttpMediaTypeNotSupportedException 以及 NoHandlerFoundException,但仍然无法解决这个错误。

有什么建议吗?

如果您正在使用 @ControllerAdvice, 这样做:

@ControllerAdvice
public class RestResponseEntityExceptionHandler 
  extends ResponseEntityExceptionHandler {
 
    @ExceptionHandler(value 
      = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

我找到了解决方案。

# Whether a "NoHandlerFoundException" should be thrown if no Handler was found to process a request.
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

错误处理代码:

@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {
    // custom logic here

    return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
}