SpringBoot 入门笔记(六)自定义异常类

只需要将自定义的异常类继承至RuntimeException即可。

示例代码:

/**
 * GirlException包含两个字段: code 和 message (message继承至RuntimeException)
 */
public class GirlException extends RuntimeException {
    private Integer code;

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

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code){
        this.code = code;
    }
}
// 在Service中使用自定义Exception
@Service
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;

    public void getAge(Integer id) {
        Girl girl = girlRepository.findById(id).get();
        Integer age = girl.getAge();

        if (age <= 10) {
            throw new GirlException(100, "你还在上小学吧");
        }

        if (age < 16) {
            throw new GirlException(101, "你可能在上中学");
        }
    }
}
// 自定义ControllerAdvice
@ControllerAdvice
public class ExceptionHandle {

    /**
     * 捕获GirlException异常
     * 启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在被 @RequestMapping 注解的方法上。
     * @param ge
     * @return
     */

    @ExceptionHandler(value = GirlException.class)
    @ResponseBody
    public Result girlHandle(GirlException ge) {
        return ResultUtil.error(ge.getCode(), ge.getMessage());
    }

    /**
     * 捕获全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        return ResultUtil.error(-1, "未知错误");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • packagetestexcrpltiom; importjava.text.ParseException; im...
    猿学阅读 5,309评论 0 2
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,246评论 4 61
  • 一、多态 1. 概述 理解:多态可以理解为事物存在的多种体(表)现形态。例如:动物中的猫和狗。猫这个对象对应的是猫...
    陈凯冰阅读 2,688评论 0 1
  • 新听说一个很有趣的词儿,仪式感。仪式感的来源倒用不着古时礼教下的那些繁琐仪式,虽然有些仍在影响我们。更多的,可能只...
    春少邪阅读 1,677评论 0 0
  • 雾都花儿阅读 994评论 0 4