Как обернуть исключение Path Not Found в Spring Boot Rest с помощью ExceptionHandler? - PullRequest
0 голосов
/ 28 января 2020

Я использую Пример Spring Boot и Spring Rest . В этом примере я передаю пользовательский заголовок, если это значение является допустимым, конечная точка вызывается успешно, если пользовательское значение заголовка неверно, то я получаю ответ ниже, который я хочу обернуть, чтобы показать его конечному пользователю, используя @ControllerAdvice ExceptionHandler .

Примечание: я прошел через 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);
}

Я реализовал HttpMessageNotReadableException и HttpMediaTypeNotSupportedException и NoHandlerFoundException, но все еще не в состоянии обернуть эту ошибку.

Есть предложения?

Ответы [ 2 ]

0 голосов
/ 09 февраля 2020

Мне удалось найти решение для этого.

# 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);
}
0 голосов
/ 28 января 2020

Если вы используете 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);
    }
}
...