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 ...
随机推荐
- webpack-工程化工具
一.简介 1.webpack 是 facebook 公司发布的一款工程化工具,早期有 react 使用. 2.核心理念: 一切都是资源,是资源我们就能模块化打包加载. 3.webpack 默认支持 c ...
- GC知识记录
2.关于Minor GC,Major GC与Full GC 1) Minor GC:即新生代的GC,指发生在新生代的垃圾收集动作.当新生代的Eden区内存不足时,就会触发Minor GC.由于对象创 ...
- 使用loadrunner编写webservice接口请求
1.使用工具: loadrunner12,本实例截图中都是loadrunner12工具 2.操作步骤: 1).新建脚本,选择Web Services协议: 2).选择工具栏: 3).点击Import, ...
- 软件安装(ubuntu) --Linux基础编程
Ubuntu:一个以桌面应用为主的开源GNU/Linux操作系统 1.在线安装(Ubuntu Example) [安装]:sudo apt-get install 安装包的名字,或者:sudo apt ...
- android------个人项目(歆语气象通新版)
歆语气象通: 歆语气象伴随你的身边,便捷生活. 包含了以下功能: 1. 天气预报数据覆盖中国城市和地区:2. 提供一周天气预报及最低最高温度,时刻关注天气,轻松计划出行:3. 各种指数详细信息,如太阳 ...
- nodejs常见问题
Js 基础问题 与前端 Js 不同, 后端是直面服务器的, 更加偏向内存方面. [Basic] 类型判断 [Basic] 作用域 [Basic] 引用传递 [Basic] 内存释放 ...
- JQuery的常用选择器 转
JQuery的常用选择器 刚开始学JQuery写的如有错误欢迎批评指正 JQuery拥有的选择器可以让我们更快更方便找到想要的元素,然后对相应的元素进行操作 简单介绍一下一些常用的选择器: 1.基本选 ...
- HDFS的上传与下载(put & get)
最近在做一个小任务,将一个CDH平台中Hive的部分数据同步到另一个平台中.毕竟我也刚开始工作,在正式开始做之前,首先进行了一段时间的练习,下面的内容就是练习时写的文档中的内容.如果哪里有错误或者疏漏 ...
- HTTPS、SSL 原理
1.1 背景知识 对称加密 :加密解密使用同一密钥,加解密速度快.随着人数增多,密钥数量急增n(n-1)/2. 非对称加密 :使用公私钥配对加解密,速度慢.公钥是从私钥中提取出来的,一般拿对方 ...
- Java加密算法
密码的常用术语: 1.密码体制:由明文空间.密文空间.密钥空间.加密算法和解密算法5部分组成. 2.密码协议:也称为安全协议,是指以密码学为基础的消息交换的通信协议,目的是在网络环境中提供安全的服务. ...