spring boot项目统一异常处理

为什么要做统一异常处理

在代码运行过程中可能抛出异常,虽然无论你用什么框架技术都会自带一个异常抛出,就比如采用spring boot框架,所有的异常处理都会映射到/error进行展示,但这种显示基本是对异常信息不做任何处理的,直接输出的,这样的话虽然对于我们程序员开发比较友好,但对于我们那些不懂编程的用户来说却很不友好。因此,我们要对这种异常信息进行处理,使其变成用户易于理解的。

在我们以前采用单体开发的过程中,可以自定义一些友好的页面去进行信息展示,但我们现在采用的是前后端分离开发,前后端的交互都是json数据,所以我们可以采用将友好的提示信息放到json里面发送给前端,前端接收到再进行渲染。

在spring boot框架中就给我们提供了@RestControllerAdvice和@ControllerAdvice两个注解结合@ExceptionHandler去解决这个问题。

首先,我们要定义一个自定异常类

@Data
public class SVNException extends RuntimeException {
​
    @ApiModelProperty(value = "状态码")
    private Integer code = 5000;
​
    @ApiModelProperty(value = "时间戳")
    private Date timestamp;
​
    @ApiModelProperty(value = "提示信息")
    private String msg;
​
    public SVNException(){
        this.timestamp = new Date();
        this.msg = "出错了出错了";
    }
​
    public SVNException(String msg){
        this.timestamp = new Date();
        this.msg = msg;
    }
}

然后在我们需要抛出异常的地方进行throw

我们也可以去改变Java自带的异常的提示信息

@RestControllerAdvice
public class GlobalExceptionHandler {
    /** 运行时异常 */
    @ExceptionHandler(RuntimeException.class)
    public RespBean runtimeExceptionHandler(RuntimeException ex) {
        return RespBean.error().setMsg("运行时异常");
    }
​
    /** 空指针异常 */
    @ExceptionHandler(NullPointerException.class)
    public RespBean nullPointerExceptionHandler(NullPointerException ex) {
        return RespBean.error().setMsg("空指针异常");
    }
​
    /** 类型转换异常 */
    @ExceptionHandler(ClassCastException.class)
    public RespBean classCastExceptionHandler(ClassCastException ex) {
        return RespBean.error().setMsg("类型转换异常");
    }
​
    /** sql异常 */
    @ExceptionHandler(SQLException.class)
    public RespBean SQLException(SQLException ex) {
        return RespBean.error().setMsg("sql异常");
    }
​
    /** IO异常 */
    @ExceptionHandler(IOException.class)
    public RespBean iOExceptionHandler(IOException ex) {
        return RespBean.error().setMsg("IO异常");
    }
​
    /** 未知方法异常 */
    @ExceptionHandler(NoSuchMethodException.class)
    public RespBean noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        return RespBean.error().setMsg("未知方法异常");
    }
​
    /** 数组越界异常 */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public RespBean indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        return RespBean.error().setMsg("数组越界异常");
    }
    /** sql语法错误异常 */
    @ExceptionHandler(BadSqlGrammarException.class)
    public RespBean BadSqlGrammarException(BadSqlGrammarException ex) {
        return RespBean.error().setMsg("sql语法错误异常");
    }
​
    /** 无法注入bean异常 */
    @ExceptionHandler(NoSuchBeanDefinitionException.class)
    public RespBean NoSuchBeanDefinitionException(NoSuchBeanDefinitionException ex) {
        return RespBean.error().setMsg("无法注入bean");
    }
​
​
    /** 400错误 */
    @ExceptionHandler({TypeMismatchException.class})
    public RespBean requestTypeMismatch(TypeMismatchException ex) {
        return RespBean.error().setMsg("请求错误");
    }
​
    /** 500错误 */
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public RespBean server500(RuntimeException ex) {
        return RespBean.error().setMsg("服务器异常");
    }
​
    /** 栈溢出 */
    @ExceptionHandler({StackOverflowError.class})
    public RespBean requestStackOverflow(StackOverflowError ex) {
        return RespBean.error().setMsg("栈溢出异常");
    }
​
    /** 除数不能为0 */
    @ExceptionHandler({ArithmeticException.class})
    public RespBean arithmeticException(ArithmeticException ex) {
        return RespBean.error().setMsg("除数不能为0异常");
    }
​
    /** 其他错误 */
    @ExceptionHandler({Exception.class})
    public RespBean exception(Exception ex) {
        return RespBean.error().setMsg("网络连接失败,请退出后再试");
    }
}
​

当然这种处理方式也不是万能的,比如当你的处理还没进入到处理的时候,它是直接跳转到"/error"视图的。不过,我们也有处理这种异常的方法。

我们可以继承ErrorController,重写里面的getErrorPath(),将里面返回的视图改成我们自定义的路径,然后在里面定义我们想要的展示方式。

@RestController
public class Exception404Handler implements ErrorController {
​
    @Override
    public String getErrorPath() {
        return "/error";
    }
​
    @RequestMapping(value = {"/error"})
    public RespBean error(HttpServletRequest request, HttpServletResponse response) {
        int status = response.getStatus();
        if (status == 404) {
            return RespBean.error().setMsg("404啦啦啦啦啦啦!!");
        }
        return RespBean.error().setMsg("错误了");
    }
​
}

总结:当遇到我们无法直接可以抓的异常,我们可以去找到它自定义的跳转路径,然后重写路径,跳到我们自定义的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值