Spring 統一異常處理

1. 本身定義的異常,繼承RuntimeException。能夠建個exception包,專門放自定義異常。自定義的異經常使用來描述本身程序中特有的異常。
 spring

public class CustomGenericException extends RuntimeException {
    private String errCode;
    private String errMsg;


    public CustomGenericException(String errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }


    public String getErrCode() {
        return errCode;
    }


    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }


    public String getErrMsg() {
        return errMsg;
    }


    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
}

2. 定義一個專用作處理異常的類,以下, @ExceptionHandler()括號中的異常類.class表示這個方法用來處理哪一種異常。mvc

@ControllerAdvice(annotations = Controller.class)
public class GlobalExceptionController {


    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomerException(CustomGenericException ex) {
        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errCode", ex.getErrCode());
        model.addObject("errMsg", ex.getErrMsg());


        return model;
    }


    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllException(Exception ex) {
        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("errMsg", "this is Exception.class");


        return model;
    }
}

3. 程序中只管拋異常就能夠, 能夠拋自定義的異常,或其餘異常,異常處理類中對應的異常處理辦法會起做用。 app

@Controller
public class MainController {
    @RequestMapping(value = "/{type}", method = RequestMethod.GET)
    public ModelAndView getPages(@PathVariable("type") String type) throws IOException {




        if("error".equals(type)) {
            throw new CustomGenericException("E888", "This is custom message");
        } else if("io-error".equals(type)) {
            throw new IOException();
        } else {
            return new ModelAndView("index").addObject("msg", type);
        }
    }


4. spring配置文件中要能掃到這些bean, 而且加上<mvc:annotation-driven/>this

<context:component-scan base-package="com.***">
</context:component-scan>


<mvc:annotation-driven/>
相關文章
相關標籤/搜索