【统一全局异常处理】3. 全局异常处理ExceptionHandler

天涯浪子 提交于 2019-12-26 11:52:50

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

一、全局异常处理器

ControllerAdvice注解的作用就是监听所有的Controller,一旦Controller抛出CustomException,就会在@ExceptionHandler(CustomException.class)对该异常进行处理。

@ControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public AjaxResponse customerException(CustomException e) {
        if (e.getCode() == CustomExceptionType.SYSTEM_ERROR.getCode()) {
            //400异常不需要持久化,将异常信息以友好的方式告知用户就可以
            //TODO 将500异常信息持久化处理,方便运维人员处理
        }
        return AjaxResponse.error(e);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResponse exception(Exception e) {
        //TODO 将异常信息持久化处理,方便运维人员处理

        //没有被程序员发现,并转换为CustomException的异常,都是其他异常或者未知异常.
        return AjaxResponse.error(new CustomException(CustomExceptionType.OTHER_ERROR, "未知异常"));
    }

}

 

二、人为制造异常测试一下

把之前的Controller的代码移到service层

@Service
public class CustomServiceImpl implements CustomService {

    /**
     * 模拟用户输入数据导致的校验异常
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getCustom(Long id) {
        if (id <= 0) {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "您输入的数据不符合业务逻辑,请确认后重新输入!");
        } else {
            Map<String, Object> m = new HashMap<String, Object>(3);
            m.put("customId", id);
            m.put("customName", "李四");
            m.put("customAge", "女");
            return m;
        }

    }

    /**
     * 模拟系统异常
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResponse putCustom(Long id) throws CustomException {
        try {
            Class.forName("com.mysql.jdbc.xxxx.Driver");
            return AjaxResponse.success();
        } catch (ClassNotFoundException e) {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "业务逻辑出现异常:ClassNotFoundException!");
        }
    }

}

 

测试

系统异常

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!