Springboot自定义异常处理

时间:2018-10-04 02:47:25   收藏:0   阅读:294

1.自定义异常类

技术分享图片
import lombok.Data;

@Data
public class UserException extends RuntimeException {
    private Long id;

    public UserException(Long id) {
        super("user not exist");
        this.id = id;
    }

    public UserException(String message, Long id) {
        super(message);
        this.id = id;
    }
}
自定义异常类

2.编写异常处理handler

技术分享图片
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ControllerExceptionHandler {
    @ExceptionHandler(UserException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String,Object> handlerUserNotExistException(UserException ex){
        Map<String,Object> result=new HashMap<>();
        result.put("id",ex.getId());
        result.put("message",ex.getMessage());
        return result;
    }
}
异常处理handler

 

3.使用过程

技术分享图片

 

原文:https://www.cnblogs.com/zqr99/p/9741266.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!