全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

前言

     本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用在 Controller 层进行 try-catch 了

一、处理思路

  1. 思路:在sevice业务逻辑层 try{}catch(){} 捕获抛出,经由contorller 层抛到 自定义全局处理类 中处理自定义异常及系统异常。

     2、实现方式:使用 @RestControllerAdvice + @ExceptionHandler 注解方式实现全局异常处

二、实现过程

 1、@RestControllerAdvice 注解定义全局异常处理类 ,@ExceptionHandler 注解声明异常处理方法。

package com.exception;

import com.response.DefaultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author wanjiadong
 * @description
 * @date Create in 11:17 2019/1/5
 */
@RestControllerAdvice
@Slf4j
public class UniteExceptionHandler {

    @ExceptionHandler({Exception.class})//拦截指定异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//指定游览器返回状态码
    public DefaultResponse uniteExceptionHandler(Exception e) {
        log.error("uniteExceptionHandler");
        return new DefaultResponse();
    }

    @ExceptionHandler(BusinessException.class)
    public DefaultResponse businessExceptionHandler(BusinessException e) {
        log.error("businessExceptionHandler:"+e.getMessage());
        return new DefaultResponse();
    }
}
package com.exception;

/**
 * @author wanjiadong
 * @description
 * @date Create in 13:52 2019/1/5
 */
public class BusinessException extends RuntimeException {

    private Integer code;

    public BusinessException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

41摄氏度男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值