springboot全局异常处理

一、使用@RestControllerAdvice

只能处理controller层返回报错,如果是dao层,则需要配合aop抛出异常,再捕获

@ControllerAdvice
public class MyExceptionHandler {
    private Logger logger = LoggerFactory.getLogger("MyExceptionHandler");

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, Object> errorHandler(Exception ex) {
        Map<String, Object> map = new HashMap<>();
        // 根据不同错误获取错误信息
        if (ex instanceof IException) {
            map.put("code", ((IException) ex).getCode());
            map.put("msg", ex.getMessage());
        } else if (ex instanceof TokenException) {
            map.put("code", ((TokenException) ex).getCode());
            map.put("msg", ex.getMessage());
        } else {
            String message = ex.getMessage();
            map.put("code", 500);
            map.put("msg", message == null || message.trim().isEmpty() ? "未知错误" : message);
            // map.put("details", message);
            logger.error(message, ex);
            ex.printStackTrace();
        }
        return map;
    }

}

二、使用切面@Aspect

@Aspect
@Slf4j
@Component
public class GlobalExceptionAspect
{
    @Pointcut("execution(* com.jooan..*.*(..))")
    public void pointcut()
    {
    }

    @AfterThrowing(pointcut = "pointcut()",
                   throwing = "e")
    public JsonResult afterThrowing(JoinPoint joinPoint, Throwable e) throws Exception
    {
        log.error("全局捕获到异常了..............",e);
        //纪录错误信息
        throw new Exception("服务器异常");
    }

}

借鉴文章链接:https://blog.csdn.net/wowwilliam0/article/details/88978659

https://blog.csdn.net/xiaoxiaole0313/article/details/104421941?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-0&spm=1001.2101.3001.4242

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值