一、页面的形式返回

  直接在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 的错误处理功能的实现的更多相关文章

  1. sql 的错误处理功能很弱

    --下面演示了SQL错误处理的脆弱性--邹建 --演示1--测试的存储过程1create proc p1asprint 12/0if @@error<>0print '发生错误1' sel ...

  2. Atitit php java python nodejs错误日志功能的比较

    Atitit php  java  python  nodejs错误日志功能的比较 1.1. Php方案 自带 1 1.2. Java解决方案 SLF4J 1 1.3. Python解决方案 自带lo ...

  3. SpringBoot自定义错误信息,SpringBoot适配Ajax请求

    SpringBoot自定义错误信息,SpringBoot自定义异常处理类, SpringBoot异常结果处理适配页面及Ajax请求, SpringBoot适配Ajax请求 ============== ...

  4. SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面

    SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...

  5. springboot自定义错误页面

    springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...

  6. 【链接】SpringBoot启动错误

    [错误解决]SpringBoot启动错误 https://blog.csdn.net/Small_Mouse0/article/details/78551900

  7. SpringBoot的注解注入功能移植到.Net平台(开源)

    *:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...

  8. SpringBoot简单实现登录功能

    登陆 开发期间模板引擎页面修改以后,要实时生效 1).禁用模板引擎的缓存 # 禁用缓存 spring.thymeleaf.cache=false 2).页面修改完成以后ctrl+f9:重新编译: 登陆 ...

  9. SpringBoot 整合Mail发送功能问题与解决

    SpringBootLean 是对springboot学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.oschina.n ...

随机推荐

  1. Hadoop2.X管理与开发

    Hadoop 2.X 管理与开发 一.Hadoop的起源与背景知识 (一)什么是大数据 大数据(Big Data),指无法在一定时间范围内用常规软件工具进行捕捉.管理和处理的数据集合,是需要新处理模式 ...

  2. HttpClient MultipartEntityBuilder 上传文件

    文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...

  3. 数据流中的中位数 Find Median from Data Stream

    2019-04-17 16:34:50 问题描述: 问题求解: class MedianFinder { PriorityQueue<Integer> smaller; PriorityQ ...

  4. mysql5.7 timestamp错误:there can be only oneTIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE

    #1293 - Incorrect table definition; there can be only oneTIMESTAMP column with CURRENT_TIMESTAMP in ...

  5. JMETER-01

    jmter安装 1.Linxu安装: 步骤:下载JMeter包-->解压包-->赋权限-->配置环境变量-->测试服务 1.下载:wget http://mirrors.hus ...

  6. IDEA外部工具配置-OpenJML篇

    帮助文档 jetbrains帮助文档:https://www.jetbrains.com/help/idea/settings-tools-external-tools.html 使用external ...

  7. .net mvc 上传头像

    我用的是mvc5  开发环境vs2017 [仅供参考] [视图代码] <div > <img src="@path" alt="@att.Count&q ...

  8. Redis基础知识小结

    Redis是一个高性能的key-value型数据库.Redis能读的速度是110000次/s,写的速度是81000次/s ,性能极高.Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全 ...

  9. css--颜色值

    首先,#000000格式的颜色被成为十六进制颜色码: 6位数分为三组,每两位数一组,依次是红.黄.蓝颜色的强度: #000000可以缩写为#000:黑色 其他类推

  10. gat和post封装代码

    from urllib import request, parsefrom urllib.error import HTTPError, URLError def get(url, headers=N ...