首页 > 解决方案 > Spring Boot Exception 不显示原因/描述

问题描述

我想通过 Spring Boot 中的一个描述性异常并且包含一个原因,即。“找不到狗”。目前我得到了异常,但它是通用的:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Apr 20 09:32:07 CEST 2021
There was an unexpected error (type=Not Found, status=404).

@Service 方法实现抛出错误:

@Service
public class DogServiceImpl implements DogService {
    @Autowired
    DogRepository dogRepository;

    public String retrieveDogBreedById(Long id){

        Optional<String> optionalBreed = Optional.ofNullable(dogRepository.findBreedById(id));
        String breed = optionalBreed.orElseThrow(DogNotFoundException::new);
        return breed;

    };

这是我的例外:

@ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Dog not found")
public class DogNotFoundException extends RuntimeException{
    public DogNotFoundException() {
    }

    public DogNotFoundException(String message) {
        super(message);
    }
}

我正在将 @RestController 用于 REST API

标签: spring-boot

解决方案


错误处理 Spring Boot Starter可以很容易地做到这一点。有关快速概述,请参阅https://foojay.io/today/better-error-handling-for-your-spring-boot-rest-apis/或https://wimdeblauwe.github.io/error-handling-spring- boot-starter/获取完整文档。

如果你只是DogNotFoundException在这样定义时抛出:

@ResponseStatus(value= HttpStatus.NOT_FOUND)
public class DogNotFoundException extends RuntimeException{
    public DogNotFoundException() {
      super("Dog not found");
    }

    public DogNotFoundException(String message) {
        super(message);
    }
}

,那么库将默认确保以下响应:

{
  "code":"DOG_NOT_FOUND",
  "message":"Dog not found"
}

(免责声明:我是图书馆的作者)


推荐阅读