要思考的问题前端
在如今的先后端交互中,一般都规范了接口返回方式,如返回的接口状态(成功|失败)以及要返回的数据在那个字段取,或者说失败了之后提示信息从接口哪里返回,所以,若是想作全局异常,而且异常发生后能准确的返回给前端解析,那么须要异常发生时返回给前端的格式与正常失败场景的格式一致。程序员
项目创建web
利用idea 工具,很容易的搭建一个SpringBoot项目,要引入的maven依赖以下:spring
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
复制代码
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
复制代码
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
复制代码
很简单,除了加入web功能还加入了咱们须要用到的JSR-303校验框架。sql
定义成功失败 返回码后端
public class Code {架构
/**
* 成功
*/
public static int SUCCESSED = 1;
/**
* 失败
*/
public static int FAILED = -1;
复制代码
}并发
定义接口返回响应实体app
public class Response implements Serializable{框架
/**
*
*/
复制代码
private static final long serialVersionUID = 4250719891313555820L;
/**
* 返回结果集
*/
复制代码
private T result;
/**
* 返回消息
*/
复制代码
private String msg;
/**
* 响应码
*/
复制代码
private Integer code;
//set get 略
}
全局异常拦截和验证
定义自定义业务异常
public class MyException extends RuntimeException {
private static final long serialVersionUID = -5875371379845226068L;
public MyException(){}
public MyException(String msg){
this.msg = msg ;
}
/**
* 异常信息
*/
private String msg ;
/**
* 具体异常码
*/
private int code = Code.FAILED;
复制代码
get set 略
编写全局异常控制器并对自定义异常作处理
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
复制代码
@ExceptionHandler(value = MyException.class)
@ResponseBody
public Response myExceptionErrorHandler(MyException ex) throws Exception {
logger.error("myExceptionErrorHandler info:{}",ex.getMessage());
Response<String> r = new Response<>();
r.setMsg(ex.getMsg());
r.setCode(ex.getCode());
return r;
复制代码
}
编写controller模拟抛出业务异常
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping(value = "/update")
Response update(User user){
//todo 此处为模拟异常抛出
if(true){
throw new MyException("更新失败");
}
//todo 此处为模拟返回
Response<Boolean> response = new Response<>();
response.setCode(Code.SUCCESSED);
response.setResult(true);
return response;
复制代码
}
}
postMan模拟请求接口,进行验证
数据绑定异常处理
一般咱们操做数据的时候,不只前端须要进行数据校验,后端也应当进行拦截和进行相应的错误提示,JSR-303校验框架也是咱们的一种选择。
编写实体User
,并对属性进行注解控制
public class User {
@NotNull(message = "用户名不能为空")
private String userName;
private int age;
复制代码
//...
全局异常控制类加入拦截
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = BindException.class)
@ResponseBody
public Response<String> bindExceptionErrorHandler(BindException ex) throws Exception {
logger.error("bindExceptionErrorHandler info:{}",ex.getMessage());
Response<String> r = new Response<>();
StringBuilder sb = new StringBuilder();
FieldError fieldError = ex.getFieldError();
sb.append(fieldError.getDefaultMessage());
r.setMsg(sb.toString());
r.setCode(Code.FAILED);
return r;
}
复制代码
//...
编写控制器
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping(value = "/add")
Response<User> add(@Validated User user){
//todo 此处为模拟返回
Response<User> response = new Response<>();
response.setCode(Code.SUCCESSED);
response.setResult(new User());
return response;
}
复制代码
//...
postMan模拟请求
不填写任何属性,模拟添加操做,准确进行拦截和报错
项目结构预览:
适合的才是最好的,每一个团队都应摸索出本身的一套异常解决方案,本文所提仅针对业务异常,但愿你们也能有所收获
欢迎工做一到五年的Java工程师朋友们加入Java程序员开发: 854393687
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用本身每一分每一秒的时间来学习提高本身,不要再用"没有时间“来掩饰本身思想上的懒惰!趁年轻,使劲拼,给将来的本身一个交代!