ERROR:严重问题,我们无法处理

EXCEPTION:RuntimeException 编译期不检查,出现问题需要我们修改代码

​ 非RuntimeException(CheckedException无这个异常类) 编译期必须处理,否则程序无法编译

​ 自定义异常继承Excepition默认为非RuntimeExcepition。

异常 可以处理 用非RuntimeException 举例:处理文件,文件路径错误。

无能为力 RuntimeException 举例:数据库请求数据,数据库无此数据。

在编写后台时,为了方便前端快速定位错误,仅仅使用java自带的异常是不够的。需要自定义处理异常。

为了便于显示,本文统一错误响应格式:

//统一错误响应
{
code:10001
message:xxxx
request:GET url
}

UnifyResponse.class

@Getter
@Setter
@AllArgsConstructor
public class UnifyResponse {
private int code;
private String message;
private String request; }

本文将异常分为两种:

  • 未知异常:对于前端开发者和用户 都是无意义。通常是服务端开发者代码逻辑问题。

    ​ 不需要将详细信息返还给前端和用户,可以统一显示服务器内部错误

  • 已知异常

定义已知异常:

HttpException.class

public class HttpException extends RuntimeException {
protected Integer code;
protected Integer httpStatusCode = 500; public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public Integer getHttpStatusCode() {
return httpStatusCode;
} public void setHttpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
}

NotFoundExcepiton.class

public class NotFoundException extends HttpException {
public NotFoundException(int code){
this.httpStatusCode = 404;
this.code = code;
}
}

处理异常:

GlobalExceptionAdvice.class:

@ControllerAdvice
public class GlobalExceptionAdvice { @Autowired
private ExceptionCodeConfiguration exceptionCodeConfiguration; //未知异常 错误码就直接硬编码为9999
@ResponseBody
@ExceptionHandler(value = Exception.class)
//如果不加这个注解,传回前端的http状态码会显示200 ok
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public UnifyResponse handleException(HttpServletRequest req, Exception e) {
UnifyResponse message = new UnifyResponse(9999,"服务器异常",req.getMethod() + ' ' + req.getRequestURI());
//未知异常方便调试,产品上线可以去掉
System.out.println(e);
return message;
} //已知异常 Http异常其中包含多种异常 错误码由程序员传入例如: throw new NotFoundException(10001);
//为什么不和上面未知异常一样使用@ResponseHandler 因为已知异常有很多种,状态码不一样,不能直接硬编码
//解决办法:在处理各种已知异常的类中添加http状态码,在返回的response中自己添加。使用ResponseEntity
@ExceptionHandler(HttpException.class)
public ResponseEntity<UnifyResponse> handleHttpException(HttpServletRequest req, HttpException e) {
UnifyResponse message = new UnifyResponse(e.getCode(),exceptionCodeConfiguration.getMessage(e.getCode()),req.getMethod() + ' ' + req.getRequestURI());
HttpHeaders httpHeaders = new HttpHeaders();
HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());
ResponseEntity<UnifyResponse> r = new ResponseEntity<>(message,httpHeaders,httpStatus);
return r;
}
}

配置类

已知异常的错误码和信息不要硬编码在异常类中,要善用properties配置类

exception-code.properties

liu.codes[0] = ok
liu.codes[999] = 服务器未知异常 liu.codes[10000] = 通用错误
liu.codes[10001] = 通用参数错误
liu.codes[10002] = 资源未找到
liu.codes[10003] = 没有找到合适的登陆处理方法
liu.codes[10004] = 令牌不合法或者过期
liu.codes[10005] = 用户未被授权
liu.codes[10006] = 登陆失败 liu.codes[20000] = 用户类通用错误
liu.codes[20001] = 用户已存在
liu.codes[20002] = 用户不存在
liu.codes[20003] = 用户密码错误
liu.codes[20004] = 获取用户wx openid失败 liu.codes[30000] = 商品类通用错误
liu.codes[30001] = 分类不存在
liu.codes[30002] = 商品信息不存
liu.codes[30003] = 主题不存在
liu.codes[30004] = complexity参数错误
liu.codes[30005] = Banner类资源不存在
liu.codes[30006] = 当前暂不支持级联获取sku-list
liu.codes[30007] = 当前暂不支持级联获取spu-list,请调用其他接口
liu.codes[30008] = 当前没有更多的商品信息了
liu.codes[30009] = Grid分类不存在
liu.codes[30010] = 请求的单品列表不存在
liu.codes[30011] = 请求的商品SaleExplain不存在

读取配置类:

ExceptionCodeConfiguration.class

@ConfigurationProperties(prefix = "liu")
@PropertySource(value = "classpath:/config/exception-code.properties")
@Component
public class ExceptionCodeConfiguration { private Map<Integer,String> codes =new HashMap<>(); public Map<Integer, String> getCodes() {
return codes;
} public void setCodes(Map<Integer, String> codes) {
this.codes = codes;
} public String getMessage(int code){
return codes.get(code);
}
}

解决读取properties中文乱码

idea:

  • File->setting->File Encoding 将Properties Files改为UTF-8编码,并将Transparent native-to-ascii 打勾。
  • 可能上述操作后properties文件全部乱码,把内容删除在重新输入就可以了。

SpringBoot异常处理(一)的更多相关文章

  1. SpringBoot异常处理统一封装我来做-使用篇

    SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...

  2. Springboot异常处理和自定义错误页面

    1.异常来源 要处理程序发生的异常,首先需要知道异常来自哪里? 1.前端错误的的请求路径,会使得程序发生4xx错误,最常见的就是404,Springboot默认当发生这种错误的请求路径,pc端响应的页 ...

  3. SpringBoot异常处理(二)

    参数校验机制 JSR-303 Hibernate 参数接收方式: URL路径中的参数 {id} (@PathVariable(name="id") int-whatever) UR ...

  4. SpringBoot 异常处理

    异常处理最佳实践 根据我的工作经历来看,我主要遵循以下几点: 尽量不要在代码中写try...catch.finally把异常吃掉. 异常要尽量直观,防止被他人误解 将异常分为以下几类,业务异常,登录状 ...

  5. 【使用篇二】SpringBoot异常处理(9)

    异常的处理方式有多种: 自定义错误页面 @ExceptionHandler注解 @ControllerAdvice+@ExceptionHandler注解 配置SimpleMappingExcepti ...

  6. springBoot异常处理

    1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...

  7. SpringBoot学习15:springboot异常处理方式5(通过实现HandlerExceptionResolver类)

    修改异常处理方式4中的全局异常处理controller package com.bjsxt.exception; import org.springframework.context.annotati ...

  8. SpringBoot学习14:springboot异常处理方式4(使用SimpleMappingExceptionResolver处理异常)

    修改异常处理方法3中的全局异常处理Controller即可 package bjsxt.exception; import org.springframework.context.annotation ...

  9. SpringBoot学习13:springboot异常处理方式3(使用@ControllerAdvice+@ExceptionHandle注解)

    问题:使用@ExceptionHandle注解需要在每一个controller代码里面都添加异常处理,会咋成代码冗余 解决方法:新建一个全局异常处理类,添加@ControllerAdvice注解即可 ...

  10. SpringBoot学习12:springboot异常处理方式2(使用@ExceptionHandle注解)

    1.编写controller package com.bjsxt.controller; import org.springframework.stereotype.Controller; impor ...

随机推荐

  1. android studio问题备注

    androidTestCompile 'com.android.support:support-annotations:25.3.1'configurations.all { resolutionSt ...

  2. CoProcessFunction实战三部曲之三:定时器和侧输出

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  3. PyQt(Python+Qt)学习随笔:formLayout的layoutRowWrapPolicy属性

    Qt Designer的表单布局(formLayout)中,layoutRowWrapPolicy用于控制表单布局中表单行的标签和输入部件之间是否换行.如图: 上图中蓝色标记圈起来的下拉列表数据是其可 ...

  4. sqlite 数据库与mysql 数据库使用区别记录

    遇到了就记点儿. 1.sqlite 中,设置外键关联,没啥用.只有mysql 中可用.

  5. aspnetcore webapi 解决发布以后每隔一段时间请求变缓慢

    项目:netcore webapi 3.1 平台:windows server 2008 r2 服务器:IIS 7.5 项目发布到IIS以后第一次请求特别慢大概7.8秒,然后每隔5分钟请求一次大概2. ...

  6. AcWing 322. 消木块

    由于木块可以由一些木块的消除,使两边相同颜色的合并 所以我们设定一个归并方式,即每个区间记录一下右边的延展性. (等于左边找右边) 设 \(f[i][j][k]\) 为\([i, j]\) 区间,右侧 ...

  7. USB接口禁用小工具v1.0.1

    由论坛用户原创制作的一个USB接口工具, 可选择手动/自动启动或者禁止启动模式, 开启禁止启动模式后USB接口将关闭识别功能, 有效防止U盘设备侵入,对于机房实验室设施来说相当管用. 下载地址:htt ...

  8. 开源抓包工具PowerSniff(支持lua,c语言作为脚本实时分析)

    做这个程序的意图是wireshark插件编写复杂(虽然也支持lua),而轻量级的工具如smartsniff,minisniff不支持插件化数据分析,各种工具用下来或多或少不顺手.以前写的外挂也都是手工 ...

  9. 一、什么是Jmeter?Jmeter安装?Jmeter的启动?

    什么是Jmeter Apache JMeter 是 Apache 组织开发的基于 Java 的压力测试工具,也可以进行接口测试.它是一个开源的,100%基于Java的应用程序,带有图形界面.它旨在分析 ...

  10. 解决Linux所有命令不能使用的问题

    解决Linux所有命令不能使用的问题 出现这个问题说明你的 /etc/profile 配置出现了问题,一般是因为path配置出现了问题.排除添加内容中的错误,然后重启一个新窗口执行执行 source ...