springboot实战原理分析笔记(十)- 异常处理
作者:互联网
异常处理
1.取消springboot默认逻辑异常处理
@SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
使用ErrorPageRegistrar方法
1.写一个类实现ErrorPageRegistrar接口,然后将这个类交给Spring容器(类似web.xml里面配置错误处理方式)
@Component
public class CommonErrorPageRegistry implements ErrorPageRegistrar{
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
errorPageRegistry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
errorPageRegistry.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
errorPageRegistry.addErrorPages(new ErrorPage(IllegalArgumentException.class, "/argsError.html"));
}
}
2.全局异常处理
1.写一个类加上@ControllerAdvice
2.写一个处理方法, 加上@ExceptionHandler
@ControllerAdvice
public class GogalExceptionHandler {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public String error(Exception e){
return "global error: " + e.getMessage();
}
}
标签:实战,errorPageRegistry,springboot,笔记,class,ErrorPage,new,public,ErrorPageRegistrar 来源: https://blog.csdn.net/fsdf8sad7/article/details/95998795