估计大家都会了的^_^,本文代码为主,在做Web应用的时候,请求处理过程中发生错误是非常常见的情况,那我们如何才能统一且友好地返回系统异常给前台呢。
关键在于:注解@ControllerAdvice和@ExceptionHandler
通过使用@ControllerAdvice定义统一的异常处理类,而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型
创建一个最简单Springboot项目
Controller层代码:
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
/**
* 访问路径 http://localhost:8080/user/finduserByTel?tel=1234567
* @param tel 手机号
* @return userName
*/
@ResponseBody
@RequestMapping("/finduserByTel")
public Result findUserNameByTel(@RequestParam("tel") String tel) throws Exception {
return userService.findUserName(tel);
}
}
Service层代码:
@Service
public class UserServiceImpl implements UserService {
@Override
public Result findUserName(String tel) throws Exception{
if (StringUtils.isEmpty(tel)) {
throw new CommonException(ResultEnum.NOT_NULL.getCode(),ResultEnum.NOT_NULL.getMsg());
}
if (tel.length() != 11) {
throw new CommonException(ResultEnum.PARAMS_INVALID.getCode(),ResultEnum.PARAMS_INVALID.getMsg());
}
System.out.println("tel:" + tel);
return ResultUtil.success(tel);
}
}
统一结果返回工具类
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setCode(ResultEnum.SUCCESS.getCode());
result.setMsg(ResultEnum.SUCCESS.getMsg());
result.setData(object);
return result;
}
public static Result success(){
return success(null);
}
public static Result error(Integer code,String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
统一结果返回枚举类
public enum ResultEnum {
//未知错误
UNKNOW_ERROR(500,"未知错误"),
SUCCESS(200,"成功"),
PARAMS_INVALID(405,"参数非法"),
NOT_NULL(406,"参数不能为空");
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
以上代码很简单,不解析,你一眼就能看懂,就是你平时写得最多的。
自定义通用异常类为了定位的错误更准确,希望不同的错误可以返回不同的错误码,所以可以自定义一个Exception
/**
* 注意要继承自RuntimeException,底层RuntimeException继承了Exception,
* spring框架只对抛出的异常是RuntimeException才会进行事务回滚,
* 如果是抛出的是Exception,是不会进行事物回滚的
*/
public class CommonException extends RuntimeException {
private Integer code;
public CommonException(Integer code,String message) {
//父类的构造方法本身会传message进去
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
创建全局异常处理类
通过使用@ControllerAdvice定义统一的异常处理类,而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型
@ControllerAdvice
public class ExceptionHandle {
/**
* @ExceptionHandler(value = Exception.class):声明要捕获的异常类
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
if(e instanceof CommonException){
CommonException commonException = (CommonException)e;
return ResultUtil.error(commonException.getCode(),commonException.getMessage());
}else {
return ResultUtil.error(ResultEnum.UNKNOW_ERROR.getCode(),ResultEnum.UNKNOW_ERROR.getMsg());
}
}
}
最后,启动该应用,访问:
http://localhost:8080/user/finduserByTel?tel=12345678910