Spring Boot-控制404未找到 [英] Spring boot - taking control of 404 Not Found

查看:1974
本文介绍了Spring Boot-控制404未找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out the simplest way to take control over the 404 Not Found handler of a basic Spring Boot RESTful service such as the example provided by Spring:

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

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

Rather than have it return the default Json output:

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

我想提供自己的Json输出.

I'd like to provide my own Json output.

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

By taking control of the DispatcherServlet and using DispatcherServlet#setThrowExceptionIfNoHandlerFound(true), I was able to make it throw an exception in case of a 404 but I can't handle that exception through a @ExceptionHandler, like I would for a MissingServletRequestParameterException. Any idea why?

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

Or is there a better approach than having a NoHandlerFoundException thrown and handled?

推荐答案

效果很好.

当您使用SpringBoot时,它不会明确处理( 404未找到),它会使用 WebMvc 错误响应.如果您的Spring Boot应该处理该异常,那么您应该对Spring Boot进行一些修改.对于404异常类,如果您想在 @RestControllerAdvice 类中处理该异常,则为 NoHandlerFoundException ,必须在Application类中添加 @EnableWebMvc 批注,在DispatcherServlet中设置 setThrowExceptionIfNoHandlerFound(true); .请参考验证码

When you are using SpringBoot it does not handle (404 Not Found) explicitly it uses WebMvc error response. If your Spring Boot should handle that exception then you should do some hack around Spring Boot. For 404 Exception class is NoHandlerFoundException if you want to handle that exception in your @RestControllerAdvice Class you must add @EnableWebMvc annotation in your Application class and set setThrowExceptionIfNoHandlerFound(true); in DispatcherServlet. Please Refer the code

@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

@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类以返回自定义的错误响应

I have created ApiError class to return customized error response

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...
}

这篇关于Spring Boot-控制404未找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆