我试图找出最简单的方法来控制基本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/