Springboot 的错误处理功能的实现
一、页面的形式返回
直接在resources的目录下创建public/error的路径,然后创建5xx.html或者4xx.html文件,如果出错就会自动跳转的相应的页面。
二、cotroller的形式返回错误的处理
1.自定义错误处理类
package com.kiyozawa.manager.error;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map; /**
* 自定义错误处理
*/
public class MyErrorController extends BasicErrorController { public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorProperties, errorViewResolvers);
} // {
// "timestamp": "2019-03-02 13:19:46.066",
// x "status": 500,
// x"error": "Internal Server Error",
// x "exception": "java.lang.IllegalArgumentException",
// "message": "编号不可为空",
// x "path": "/manager/products"
// } @Override
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
//去除返回值中不必要的信息
attrs.remove("timestamp");
attrs.remove("status");
attrs.remove("error");
attrs.remove("exception");
attrs.remove("path");
//通过信息获取errorCode的值,最终获取errorEnum类的信息
String errorCode = (String) attrs.get("message");
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
//ErrorEnum类的信息存入attrs中返回给前端
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
return attrs;
}
}
把错误处理类自动配置到Springboot中
package com.kiyozawa.manager.error; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorViewResolver;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.List; @Configuration
public class ErrorConfiguration {
@Bean
public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
return new MyErrorController(errorAttributes, serverProperties.getError(),
errorViewResolversProvider.getIfAvailable());
}
}
自定义错误类型
package com.kiyozawa.manager.error; public enum ErrorEnum {
ID_NoT_NULL("F001","编码不为空",false),
UNKOWN("000","位置异常",false);
private String code;
private String message;
private boolean canRetry;
ErrorEnum(String code,String message,boolean canRetry){
this.code=code;
this.message=message;
this.canRetry=canRetry;
}
public static ErrorEnum getByCode(String code){
for (ErrorEnum errorEnum:ErrorEnum.values()){
if(errorEnum.code.equals(code)){
return errorEnum;
}
}
return UNKOWN; } public String getCode() {
return code;
} public String getMessage() {
return message;
} public boolean isCanRetry() {
return canRetry;
}
}
另外的一种方式见下:
package com.kiyozawa.manager.error; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap;
import java.util.Map; /**
* 统一错误处理
*/
//路径为controller类的路径
@ControllerAdvice(basePackages = {"com.kiyozawa.manager.controller"})
public class ErrorControllerAdvice {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity handleException(Exception e){
Map<String, Object> attrs = new HashMap();
String errorCode = e.getMessage();
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
attrs.put("type","advice");
// Assert.isNull(attrs,"advice");
return new ResponseEntity(attrs, HttpStatus.INTERNAL_SERVER_ERROR);
} }
Springboot 的错误处理功能的实现的更多相关文章
- sql 的错误处理功能很弱
--下面演示了SQL错误处理的脆弱性--邹建 --演示1--测试的存储过程1create proc p1asprint 12/0if @@error<>0print '发生错误1' sel ...
- Atitit php java python nodejs错误日志功能的比较
Atitit php java python nodejs错误日志功能的比较 1.1. Php方案 自带 1 1.2. Java解决方案 SLF4J 1 1.3. Python解决方案 自带lo ...
- SpringBoot自定义错误信息,SpringBoot适配Ajax请求
SpringBoot自定义错误信息,SpringBoot自定义异常处理类, SpringBoot异常结果处理适配页面及Ajax请求, SpringBoot适配Ajax请求 ============== ...
- SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面
SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...
- springboot自定义错误页面
springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...
- 【链接】SpringBoot启动错误
[错误解决]SpringBoot启动错误 https://blog.csdn.net/Small_Mouse0/article/details/78551900
- SpringBoot的注解注入功能移植到.Net平台(开源)
*:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...
- SpringBoot简单实现登录功能
登陆 开发期间模板引擎页面修改以后,要实时生效 1).禁用模板引擎的缓存 # 禁用缓存 spring.thymeleaf.cache=false 2).页面修改完成以后ctrl+f9:重新编译: 登陆 ...
- SpringBoot 整合Mail发送功能问题与解决
SpringBootLean 是对springboot学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.oschina.n ...
随机推荐
- OO随笔
第一次作业——多项式计算 1.自我程序分析 第一次作业是多项式计算,只使用了一个多项式类.第一次接触面向对象的程序,还比较生疏,不是很能理解面向对象的思想.将读入,处理,计算,都放到了main函数中, ...
- npm ERR! File exists: /XXX/xxx npm ERR! Move it away, and try again.
今天抽空将我的静态服务 ks-server 之前留下的 bug(在node低版本情况下报错)维护了一下. 当我重新 npm link 时,如下错误: npm WARN ks-server@1.0.2 ...
- Commander
原文:https://www.npmjs.com/package/commander Commander.js Installation npm install commander --save Op ...
- document.body.scrollTop和document.documentElement.scrollTop 以及值为0的问题
转自http://wo13145219.iteye.com/blog/2001598 一.先遇到document.body.scrollTop值为0的问题 做页面的时候可能会用到位置固定的层,读取do ...
- linux上docker安装centos7.2
1.安装 docker pull centos:7.2.1511 2.启动镜像 docker run -d -i -t <IMAGE ID> /bin/bash 3.进入容器 docker ...
- linux 下的read write 和fread fwrite
待进一步测试啊,先占坑 --------2017/7/17 忘记之前要写什么了,只记得当时测试完得出的结论是,无论是写设备还是写文件,都用read/write是既安全又省事情的举动.还熟悉. 尽多少力 ...
- 版本控制commit和update过程
很早就使用了git.后来还管了一个VSS,但长时间以来git和VSS基本都当ftp使用,顶多知道其有回退旧版本的功能,但对“版本控制”这个词一直以来都没领会其内含. 比如我一直担心两个问题,一是拉取下 ...
- npm run build 打包后,如何运行在本地查看效果(Nginx服务)
这段时间,研究了一下vue 打包的很慢的问题.但是当我 npm run build 打包后,在本地查看效果的时候,活生生被我老大鄙视了,因为我打开了XAMPP.他说:你怎么不用Nginx啊?用这个一堆 ...
- express应用程序生成器
1.express 是node.js的后端开发框架,angular是node.js 的前端开发框架 2.express 的三个核心概念:路由.中间件.模板引擎 一.安装express应用服务程序生成器 ...
- Kali Linux搭建Go语言环境
准备: (1)Kali Linux系统(此实验为VMware环境) (2)Go语言安装包 具体过程: (1)到官网下载Go语言安装包,如图示操作(官网可能需要梯子,没有的可以从国内相关网站下载) ( ...