Spring Boot 2.2.5 404 страница не найдена custom json ответ - PullRequest
0 голосов
/ 01 апреля 2020

Как мне получить пользовательский json для моих 404 страниц? на самом деле мне нужно создавать собственные json ошибки для моего приложения. например, для 404,401,403,422, ... Я много искал и нашел:

package ir.darsineh.lms.http.exceptionHandler;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {


    @ExceptionHandler(NoHandlerFoundException.class)
    public void springHandleNotFound(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.NOT_FOUND.value());
    }


}

, и вот ошибка, которую я получаю:

Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]

Мне нужно мое тело ответа API json быть примерно таким:

{"code": 404, "message": "page not found"}

Ответы [ 2 ]

2 голосов
/ 01 апреля 2020

Во-первых, вы должны позволить Spring MVC генерировать исключение, если обработчик не найден:

spring.mvc.throw-exception-if-no-handler-found=true

Затем исключение должно быть перехвачено с помощью @ControllerAdvice:

@ControllerAdvice
public class CustomAdvice {

    // 404
    @ExceptionHandler({ NoHandlerFoundException.class })
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public CustomResponse notFound(final NoHandlerFoundException ex) {
        return new CustomResponse(HttpStatus.NOT_FOUND.value(), "page not found");
    }
}

@Data
@AllArgsConstructor
class CustomResponse {
    int code;
    String message;
}

Не забудьте добавить аннотацию @ EnableWeb Mvc в ваше приложение.

0 голосов
/ 01 апреля 2020

В классе ResponseEntityExceptionHandler уже есть метод handleNoHandlerFoundException (), определенный ниже.

protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    return this.handleExceptionInternal(ex, (Object)null, headers, status, request);
}

Поскольку сигнатуры методов (родительский класс и наш класс реализации) различаются, это привело к неоднозначной ошибке. Использование той же подписи переопределит вышеуказанный метод с нашей пользовательской реализацией.

@ExceptionHandler(NoHandlerFoundException.class)
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    ErrorResponse error = new ErrorResponse("404", "page not found");
    return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}

Надеюсь, это поможет !!

...