小编典典

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

spring-boot

我正在使用Spring Boot和Spring
Rest示例。在此示例中,我传递了自定义标头,如果该值有效,则端点被成功调用,如果自定义标头值不正确,则得到下面的响应,我想使用@ControllerAdviceExceptionHandler
将其包装为显示给最终用户。

注意:我经历了[pring mvc-如何将所有错误的请求映射到单个方法,但是在我的情况下,我基于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);
}

我已经实现了HttpMessageNotReadableExceptionHttpMediaTypeNotSupportedExceptionNoHandlerFoundException,但仍然无法包装此错误。

有什么建议么?


阅读 444

收藏
2020-05-30

共1个答案

小编典典

我能够找到解决方案。

# 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);
}
2020-05-30