gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:57:04 26 4
gpt4 key购买 nike

我正在使用 Spring Boot 和 Spring Rest 示例。在此示例中,我传递自定义 header ,如果该值有效,则端点被成功调用,如果自定义 header 值不正确,则我得到以下响应,我想将其包装到使用 @ 显示给最终用户ControllerAdvice 异常处理程序。

注意:我经历了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"
}

Controller

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

关于spring - 如何使用 ExceptionHandler 在 Spring Boot Rest 中包装 Path Not Found 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59950440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com