项目中统一处理异常的方式

在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。

GlobalExceptionHandler 异常处理类

import cc.ewell.dripping.product.vitalsigns.exception.BizException;
import cc.ewell.dripping.product.vitalsigns.exception.ErrorInfo;
import cc.ewell.dripping.product.vitalsigns.exception.ExceptionConfig;
import lombok.extern.slf4j.Slf4j;
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;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorInfo jsonErrorHandler(BizException e) {
        log.info("业务异常",e);
        ErrorInfo r = new ErrorInfo();
        r.setMessage(e.getMessage());
        r.setCode(e.getCode());
        return r;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorInfo jsonErrorHandler(Exception e) {
        log.error("系统异常",e);
        ErrorInfo r = new ErrorInfo();
        r.setMessage(e.getMessage());
        r.setCode(“10000”);
        return r;
    }

}

ErrorInfo 类

public class ErrorInfo {

    private String code;

    private String message;

    public String getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

BizException 类,spring 对于 RuntimeException 异常才会进行事务回滚。

public class BizException extends RuntimeException{

    private String code;

    private String message;

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

    public String getCode() {
        return code;
    }

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

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

测试类:

@RestController
@RequestMapping("/user")
public class UserController {
   
    @GetMapping("getAge")
    public void getAge(@RequestParam("age") Integer age) {
        if(age % 2 == 0){
            throw new BizException("101","年龄为偶数");
        }

    }
}

访问:http://localhost:8080/user/getAge?age=20 页面会提示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值