目录
1)DefaultHandlerExceptionResolver
2)AnnotationMethodHandlerExceptionResolver
3)SimpleMappingExceptionResolver
4)ResponseStatusExceptionResolver
2)EmbeddedServletContainerCustomizer
全部以404错误、webapp/templates/error-404.html为例
1.ExceptionResolver
主要方法:resolveException
一共有四种实现类:
1)DefaultHandlerExceptionResolver
将Exception转换为错误码
Exception | Error Code |
---|---|
ConversionNoSupportedException HttpMessageNotWritableException | 500 |
HttpMediaTypeNotAcceptableException | 406 |
HttpMediaTypeNotSupporteException | 415 |
HttpMessageNotReadableException MissingServletParameterException TypeMismatchException | 400 |
HttpRequestMethodNotSupportedException | 405 |
NoSuchHandingMethodException | 404 |
可以在web.xml中配置
<error-page>
<error-code>404</error-code>
<location>/templates/error-404.html</location>
</error-page>
也可以重写resolveException方法来处理异常(或者重写handleXXException()方法来处理特定异常)
@Bean
public DefaultHandlerExceptionResolver resolver(){
return new DefaultHandlerExceptionResolver(){
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
……
}
}
}
2)AnnotationMethodHandlerExceptionResolver
对同一个类中的Handler方法抛出的错误进行处理
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public ModelAndView handleException(RuntimeException re,HttpRequest request){
return new ModelAndView("error-404");
}
3)SimpleMappingExceptionResolver
@Bean
public SimpleMappingExceptionResolver simpleResolver(){
SimpleMappingExceptionResolver resolver=new SimpleMappingExceptionResolver();
resolver.addStatusCode("error-404",404);
return resolver;
}
4)ResponseStatusExceptionResolver
@Bean
public ResponseStatusExceptionResolver resolver(){
return new ResponseStatusExceptionResolver(){
@Override
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if(responseStatus.value()== HttpStatus.NOT_FOUND)
return new ModelAndView("error-404");
//对其他错误码继续处理
……
}
};
}
需要配合@ResponseStatus注解
2.Spring Boot增加的两种方法:
1)ErrorController:
主要思路:把错误都集中到一个路径下,然后再根据状态码分别处理(有点像Servlet的init()方法集合了所有HTTP请求的处理,但是又分派到各种doXXXX方法分别处理)
@Controller
public class ErrorProcessController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletResponse response){
int statusCode = response.getStatus();
if(statusCode == 404){
return "error-404";
}else{
//继续对其他错误码进行处理
……
}
}
@Override
public String getErrorPath() {
return "/error";
}
}
2)EmbeddedServletContainerCustomizer
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return container -> {
ErrorPage page404=new ErrorPage(HttpStatus.NOT_FOUND,"/404");
container.addErrorPages(page404);
};
}
然后再在Controller中对"/404"请求处理,返回"error-404"即可
也可以直接返回"error-404.html",不过需要放在static目录下