【问题标题】:Custom Exception throw in Spring Boot ApplicationSpring Boot 应用程序中的自定义异常抛出
【发布时间】:2019-04-30 19:23:32
【问题描述】:

我想使用 @ControllerAdvice@ExceptionHandler 在我的 Spring Boot 应用程序中创建一些自定义异常,但我可以将异常详细信息作为 json 获取

我尝试了每件事都找不到解决方案。 ErrorDetails 是我使用 setter 和 getter 的类,StringNotFoundException 是扩展异常的类

    @ControllerAdvice()
    public class RestExceptionHandler {

    @Autowired
    Environment environment;

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ExceptionHandler(StringNotFoundException.class)
    @ResponseBody
    public ErrorDetails handleNotFoundException(StringNotFoundException ex, HttpServletRequest request) {

        ErrorDetails ed = new ErrorDetails();
        ed.setErrorCode("10000");
        ed.setErrorMessage(ex.getMessage());
        ed.setErrorDescription("Try");
        ed.setPort(environment.getProperty("local.server.port"));
        ed.setUrl(request.getRequestURI().toString());
        System.out.println(ed + "****************");
        return ed;}}

在控制器中我使用这个:

if (companyList.isEmpty()) {
throw new StringNotFoundException();
            }

控制台上显示异常详细信息,但我无法获取 json 格式

com.ffi.financialcompany.exception.StringNotFoundException

【问题讨论】:

  • 我不这么认为 handleNotFoundException 方法被执行
  • 是的,它没有执行..我调试了..但不明白原因。

标签: java


【解决方案1】:

尝试让 RestExceptionHandler 扩展 ResponseEntityExceptionHandler。

ResponseEntityExceptionHandler 是 Spring 框架用来抛出异常的一个类。我认为您应该扩展该课程以解决此问题。

    @ControllerAdvice()
    public class RestExceptionHandler extends  ResponseEntityExceptionHandler {
    ....

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 2020-08-17
    • 2023-03-04
    • 2018-09-06
    • 2023-03-12
    • 2020-03-15
    • 2016-07-11
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多