您的位置:首页 > 博客中心 > 编程语言 >

SpringBoot自定义异常处理

时间:2022-03-29 01:52

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

技术分享图片

 

本类排行

今日推荐

热门手游