天天看點

項目中統一處理異常的方式

在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 頁面會提示:

項目中統一處理異常的方式