java - Spring Boot-控制404未找到

标签 java json spring rest http-status-code-404

我试图找出最简单的方法来控制基本Spring Boot RESTful服务的404 Not Found处理程序,例如Spring提供的示例:

https://spring.io/guides/gs/rest-service/

而不是让它返回默认的Json输出:

{
  "timestamp":1432047177086,
  "status":404,
  "error":"Not Found",
  "exception":"org.springframework.web.servlet.NoHandlerFoundException",
  "message":"No handler found for GET /aaa, ..."
}

我想提供自己的Json输出。

通过控制DispatcherServlet并使用DispatcherServlet#setThrowExceptionIfNoHandlerFound(true),我能够使它在404的情况下引发异常,但是我无法通过@ExceptionHandler处理该异常,就像我的MissingServletRequestParameterException一样。知道为什么吗?

还是有比抛出并处理NoHandlerFoundException更好的方法?

最佳答案

它工作得很好。

当您使用SpringBoot时,它不会显式处理( 404未找到),但会明确使用 WebMvc 错误响应。如果您的Spring Boot应该处理该异常,那么您应该对Spring Boot进行一些修改。对于404异常类,它是 NoHandlerFoundException 如果要在 @RestControllerAdvice 类中处理该异常,则必须在应用程序类中添加 @EnableWebMvc 批注,并设置 setThrowExceptionIfNoHandlerFound(true); DispatcherServlet中的。请引用代码

@SpringBootApplication
@EnableWebMvc
public class Application {  
    @Autowired
    private DispatcherServlet servlet;

    public static void main(String[] args) throws FileNotFoundException, IOException {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner getCommandLineRunner(ApplicationContext context) {
        servlet.setThrowExceptionIfNoHandlerFound(true);
        return args -> {};
    }
}

之后,您可以在 @RestControllerAdvice 类中处理 NoHandlerException
@RestControllerAdvice
public class AppException {

    @ExceptionHandler(value={NoHandlerFoundException.class})
    @ResponseStatus(code=HttpStatus.BAD_REQUEST)
    public ApiError badRequest(Exception e, HttpServletRequest request, HttpServletResponse response) {
        e.printStackTrace();
        return new ApiError(400, HttpStatus.BAD_REQUEST.getReasonPhrase());
    }
}   

我创建了ApiError类以返回自定义的错误响应
public class ApiError {
    private int code;
    private String message;
    public ApiError(int code, String message) {
        this.code = code;
        this.message = message;
    }
    public ApiError() {
    }   
    //getter & setter methods...
}

关于java - Spring Boot-控制404未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30329543/

相关文章:

java - 如何不断地显示形状,但仍然重新绘制屏幕?

json - 将 JSON 数组值映射到结构特定变量

javascript - javamail.setFrom() 在我的 spring 项目中不起作用

c# - 如何在 C# 中获取嵌套的 JSON 值?

python - 使用 Django 翻译 json 文件

java - SecurityFilterChain Bean 不保护应用程序

spring - ISO货币 list

java - 如何在项目级别配置log4j?

java - java中多种格式的日期绑定(bind)器

java - 'synchronized'是什么意思?