标签:log stack 自定义 test lex sources oba image source
/error
处理所有错误的映射,所有我们平时程序出错会弹出如下第二张图页面例如,要映射404
到静态HTML文件,您的目录结构如下:
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
要5xx
使用FreeMarker模板映射所有错误,您的目录结构如下:
src/
+- main/
+- java/
| + <source code>
+- resources/
+- templates/
+- error/
| +- 5xx.ftlh
+- <other templates>
通俗易懂的说,就是在resources目录下建立public目录,在里面新建error目录,在error目录下新建错误页面,页面名称以状态码命名:404.html,或者:4xx.html(表示以4开头的状态异常都跳转该页面),或者在templates下新建error目录,在里面新建错误页面,命名:404.html,同public目录。
@ControllerAdvice+@ExceptionHandler处理全局异常;底层是 ExceptionHandlerExceptionResolver 支持的
@ControllerAdvice
@Slf4j
public class GlobalException extends Exception{
@ExceptionHandler({FileUploadException.class, MaxUploadSizeExceededException.class})
public String test(Exception e){ //括号里的异常,是捕捉到的异常封装进去的
log.error("e="+e);//打印异常信息
return "error/500";
}
}
@ResponseStatus+自定义异常 ;底层是 ResponseStatusExceptionResolver ,把responsestatus注解的信息底层调用 response.sendError(statusCode, resolvedReason);tomcat发送的/error
//抛出自定义的异常,根据默认规则,发生指定异常时,会自动跳转对应的错误页
//value = HttpStatus.FORBIDDEN,对应着状态码
//reason = "这是什么状态码?",代表抛出的异常信息
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "这是什么状态码?")
public class CustomException extends Exception{
public CustomException() {
super();
}
public CustomException(String message) {
super(message);
}
}
实现HandlerExceptionResolver接口
@Order(value = Ordered.HIGHEST_PRECEDENCE)//优先级,数字越小,优先级越高
@Component//将组件加载到容器中进行管理
public class CustomerDefaultException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o,
Exception e) {
try {
//511是自定义状态码
httpServletResponse.sendError(511,"自定义默认异常解析器");
} catch (IOException ioException) {
ioException.printStackTrace();
}
return new ModelAndView();
}
}
标签:log stack 自定义 test lex sources oba image source
原文地址:https://www.cnblogs.com/letgofishing/p/14407012.html