美文网首页
SpringBoot 入门笔记(六)自定义异常类

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

作者: MonroeShen | 来源:发表于2019-02-08 13:21 被阅读0次

只需要将自定义的异常类继承至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, "未知错误");
    }
}

相关文章

网友评论

      本文标题:SpringBoot 入门笔记(六)自定义异常类

      本文链接:https://www.haomeiwen.com/subject/sdansqtx.html