springboot自定义异常处理

前言

spring项目中controller作为项目调用的入口,将去调用service层的接口,先在为了能统一处理service抛出到controller的异常。解决思路如下:

  1.   实现一个自定义异常。
  2.   使用@ControllerAdvice对controller自定义异常进行拦截处理。
public class AnimalNotExistException extends RuntimeException{

    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public AnimalNotExistException(Integer id){
        super("该动物不存在!" + id);
    }
}

service接口如下:

@Service
public class AnimalServiceImpl implements AnimalService{

    @Override
    public Animal getAnimal(Integer id) {
        throw new AnimalNotExistException(id);
    }
}

异常捕获方法

@ControllerAdvice
public class AnimalControllerException {

    @ExceptionHandler(AnimalNotExistException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String,Object> handlerAnimalNotExistsException(AnimalNotExistException exception){
        Map<String,Object> result = new HashMap();
        result.put("code","999");
        System.out.println(exception.getId() + ":返回异常错误信息!");
        return result;
    }
}
现在只要service抛出异常,统一返回结果{"code":"999"}

猜你喜欢

转载自blog.csdn.net/fu250/article/details/80291822