异常的分类
异常分为两种
- 自定义异常
- 系统异常
自定义异常
在开发时,对异常情况进行封装的异常,比如参数校验不通过,文件不存在的异常。这些异常信息需要返回给客户端,所以通常带有错误代码和错误信息
系统异常
这个时系统在运行的过程中,我们无法预料的异常,比如除 0 异常,数据库连接断开异常。这些异常不需要告知客户端详细信息,只需要告知客户端“服务器出错”,并且将错误信息写入日志,以供后端人员 debug。
SpringBoot中的全局异常处理
需要用到 ControllerAdvice
注解
import com.ikutarian.yuejia.vo.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局异常处理
* 异常分为两种:1)自定义异常 2)系统错误异常
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 自定义异常的处理
*/
@ResponseBody
@ExceptionHandler(value = BaseRunTimeException.class)
public Result jsonErrorHandler(BaseRunTimeException e) throws Exception {
return Result.error(e.getCode(), e.getMessage());
}
/**
* 系统错误异常
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Result errorHandler(Exception e) {
// TODO 写入日志
return Result.error(ResultEnum.SYSTEM_ERROR.getCode(), ResultEnum.SYSTEM_ERROR.getMsg());
}
}
自定义异常都继承与 BaseRunTimeException
类
import lombok.Getter;
@Getter
public class BaseRunTimeException extends RuntimeException {
private Integer code;
public BaseRunTimeException(Integer code, String msg) {
super(msg);
this.code = code;
}
}
网友评论