码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot自定义异常处理

时间:2018-10-04 09:27:03      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:one   note   hash   server   exist   image   lombok   ring   技术   

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.使用过程

技术分享图片

 

Springboot自定义异常处理

标签:one   note   hash   server   exist   image   lombok   ring   技术   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!