spring/springmvc 全局异常处理

2018-09-18  本文已影响22人  G先生_海林

1.在项目中为什么要统一异常处理

2.如何做统一异常处理?

2.1统一异常处理类

@ControllerAdvice: @ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法,可以将异常处理和controller层分开 需要配合 @ExceptionHandler 使用

代码实例:

/**
***@author hai6
**@ControllerAdvice 处理所有controller 中所有没有被try catch 包裹的注解
*/
'''

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> handlerException(){
        Map<String, Object>  map= new HashMap<String,Object>();
        map.put("code", 500);
        map.put("msg", "请稍后再试");
        return map;
    }
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Map<String, Object> handlerBusinessException(BusinessException business){
        Map<String, Object>  map= new HashMap<String,Object>();
        map.put("code", business.getCode());
        map.put("msg",business.getMsg());
        return map;
    }
}

2.2自定义异常类

继承RuntimeException 也可以继承Exception 运行时的异常我们一般都会继承 RuntimeException

异常继承.png

代码实例:

/**
 * @author hai6
 *
 */
public class BusinessException extends RuntimeException{
 
    private static final long serialVersionUID = 8751160949113891470L;
    private int code;
    private String msg;
    private String desc;
    
    
    public BusinessException(){}
    
    
    public BusinessException(int code, String msg) {
        
        this.code=code;
        this.msg=msg;
    }
    
    
    
    public BusinessException(int code, String msg, String desc) {
        super();
        this.code = code;
        this.msg = msg;
        this.desc = desc;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
}

2.3 在controller 层中使用全局异常


/**
 * @author hai6
 * @date 2018年9月16日下午2:56:39
 *
 */

@Controller
public class WebAppController {
    
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        //运行时异常
        int i=1;
        int b=i/0;//有异常
        return "test";
    }
    
    @RequestMapping("/test2")
    @ResponseBody
    public String test2() throws BusinessException{
        //抛出异常
        throw  new BusinessException(500,"出错啦");
    }
}

运行效果如下


test2.png
test.png

思考:在项目中我们有很多自定义的异常信息,请思考一下如果异常信息增多你会如何设计并处理异常会更加简洁?

上一篇 下一篇

猜你喜欢

热点阅读