spring - 未找到Spring Boot 2.2.5 404页面自定义json响应

标签 spring spring-boot rest error-handling

如何为我的404页面使用自定义json?
实际上,我需要的是能够为我的应用程序创建自定义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"}

最佳答案

首先,如果未找到处理程序,则应让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;
}

不要忘记将@EnableWebMvc批注添加到您的应用程序。

关于spring - 未找到Spring Boot 2.2.5 404页面自定义json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60960881/

相关文章:

java - Spring JPA 使用 LocalDateTime 获取 mongo 中某个范围(含)之间的日期

java - Spring 在 Filter 中使用 @Value 注解

java - 在 Spring Boot 应用程序中使用 AspectJ 加载时间编织时构建结果不一致

Java 8Optional.ofNullable.map产生非静态方法引用错误

java - 为什么 Spring 优先处理 405 Http Error 而不是 406 Http Error

java - Hibernate - 多对多实现

rest - 如何在 Spring Boot Web 应用程序中保护 REST API?

spring - Dockerfile无法使用Maven构建应用-此构建未指定目标

c# - 如何使用 ASP.NET Web API 提取并验证授权 header 中的 SAML token ?

http - REst GET 与大消息正文的 POST