如何使用 ExceptionHandler 包装 Spring Boot Rest 中找不到路径异常?



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

注意:我经历了Spring 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,但仍然无法包装此错误。

有什么建议吗?

我能够找到解决方案。

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

如果您使用的是@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);
}
}

相关内容

  • 没有找到相关文章

最新更新