Spring Boot 2.2.5 page 404 introuvable réponse json personnalisée
mhndev:
Comment puis-je avoir un json personnalisé pour mes 404 pages? en fait, ce dont j'ai besoin est de pouvoir créer des erreurs json personnalisées pour mon application. par exemple pour 404,401,403,422, ... j'ai beaucoup cherché et ce que j'ai trouvé est:
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());
}
}
et voici l'erreur que j'obtiens:
Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]
J'ai besoin que mon corps de réponse API json ressemble à ceci:
{"code": 404, "message": "page not found"}
Hamid Mohayeji:
Tout d'abord, vous devez laisser Spring MVC lever une exception si aucun gestionnaire n'est trouvé:
spring.mvc.throw-exception-if-no-handler-found=true
Ensuite, l'exception doit être interceptée à l'aide d'un @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;
}
N'oubliez pas d'ajouter l'annotation @EnableWebMvc à votre application.