spring boot 全局处理异常

在spring中,可以定义一个全局异常处理handler,当有异常的时候,进行拦截处理。

import com.idss.argus.common.Constant;
import com.idss.argus.common.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@ControllerAdvice
public class

GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     *  最大兜底异常,跳500页面
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    //设置 response 状态码
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> jsonHandler(HttpServletRequest request,Exception e) throws Exception {
        e.printStackTrace();
        return ResponseUtil.buildResultMap(Constant.STATUS_FAIL, null, "程序异常", null);
    }

    /**
     *  资产校验异常
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = IdssArgusException.class)
    @ResponseBody
    public Map<String, Object> handleIdssArgusException(IdssArgusException e) throws Exception {
        return ResponseUtil.buildResultMap(Constant.STATUS_FAIL,null,e.getErrorList(),null);
    }

}
  • validated 数据校验
    @Validated 数据校验,失败的话会抛出MethodArgumentNotValidException 异常,这样我们可以利用这个特性,做全局校验,进行异常返回。

  • 业务层的异常
    需要自己自定义异常,然后在handler中进行处理,这样就不需要在Controller中进行异常处理了。

//业务类异常
public class BusinessException extends RuntimeException {

    public BusinessException(String message){
        super(message);
    }
}
@Service
public class DogService {

    @Transactional
    public Dog update(Dog dog){

        // some database options

        // 模拟狗狗新名字与其他狗狗的名字冲突
        BSUtil.isTrue(false, "狗狗名字已经被使用了...");

        // update database dog info

        return dog;
    }

}
public static void isTrue(boolean expression, String error){
    if(!expression) {
        throw new BusinessException(error);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值