## springboot全局异常的捕获和处理

springboot全局异常的捕获和处理

这套全局异常捕捉,是springboot自带的,只需要加入以下配置即可完成。
下面的配置有必要解释一下,直接粘贴进去是会出错的



这段配置是resfull风格的返回结果类,这段配置逻辑可以自己写。捕获到了异常怎么做处理

return HttpResult.error(1405, e.getMessage());

然后我有些异常是自定义的异常,大家不懂的可以自行百度,下面是代码,非常简洁

package com.louis.mango.admin.config;

import com.quake.core.exception.QuakeException;
import com.quake.core.exception.TransactionException;
import com.quake.core.http.HttpResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常的捕获
 *
 * @author hansen
 * @version 1.0
 * @date 2019/11/13 15:04
 */
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value = {HansenException.class, RuntimeException.class, TransactionException.class})//指定拦截的异常
    @ResponseBody
    public HttpResult errorHandler(Exception e) throws Exception {
        if (e instanceof HansenException) {
            return HttpResult.error(1405, e.getMessage());
        } else if (e instanceof TransactionException) {
            return HttpResult.error(1403,"事务异常");
        }
        return HttpResult.error(1401, "未知异常");
    }
}

原文链接:https://www.hsenzy.com/archives/274

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值