【问题标题】:@exceptionhandler not working in Spring REST@exceptionhandler 在 Spring REST 中不起作用
【发布时间】:2018-12-10 10:21:57
【问题描述】:

我是 Spring REST 的初学者,正在 Spring REST 中实现异常处理。以下是抛出自定义异常的控制器代码

@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountries() throws CountryNotFoundException{

    throw new CountryNotFoundException();

    //List<Country> listOfCountries = countryService.getAllCountries();
    // return listOfCountries;
}

@ExceptionHandler(CountryNotFoundException.class)
public ResponseEntity<ErrorMessage> handleException(HttpServletRequest req, Exception e)
{
    ErrorMessage error = new ErrorMessage("Custom handler message "+e.toString(), req.getRequestURI());
    return new ResponseEntity<ErrorMessage>(error,HttpStatus.NOT_FOUND);

}

尽管如此,处理程序没有执行,我得到以下异常:

HTTP Status 500 - Request processing failed; nested exception is 
org.arpit.java2blog.exception.CountryNotFoundException

有人可以告诉我是否有任何其他配置需要处理程序才能执行?

编辑:当我将 ResponseEntity 的参数更改为 String 时,它可以工作,但不能使用 ErrorMessage。为什么会发生这种行为?

【问题讨论】:

  • 尝试将返回类型更改为字符串。
  • 我猜CountryNotFoundException 不是RuntimeException
  • 您是否也可以尝试例如执行以下操作以检查您的异常是否使用几个不同的输入参数被抛出?如:ResponseEntity&lt;String&gt; handleCountryNotFound(CountryNotFoundException e){ return ResponseEntity.status(404).entity("not found").build()}然后看看有没有被调用/捕获?
  • 您是否定义了CountryNotFoundException 来扩展Exception
  • @DforTye 不,它扩展了 RuntimeException..

标签: java spring spring-mvc spring-restcontroller


【解决方案1】:

请关注我的post 进行异常处理。我创建了示例项目以获得更详细的参考,可以找到here

【讨论】:

  • 感谢您的回答。当我将 ResponseEntity 的参数更改为字符串而不是自定义错误类时,它运行正常。但是对于自定义错误消息参数,它没有。你能告诉我为什么吗?
【解决方案2】:

试试这个

import com.fasterxml.jackson.annotation.JsonProperty;

public class ErrorMessage {

    @JsonProperty
    private final String message;

    @JsonProperty
    private final String requestURI;

    public ErrorMessage(String message, String requestURI) {
        this.message = message;
        this.requestURI = requestURI;
    }
}

【讨论】:

  • 这太棒了。在我遇到的所有示例中,我没有看到处理程序的此类注释。这个版本是 spring 特有的吗?
  • 不,它不是特定于版本的。 Spring 尝试使用HttpMessageConverterResponseEntity&lt;?&gt; 转换为响应。为了告诉 Jackson ErrorMessage 可以序列化为 json,我们使用 @JsonProperty
猜你喜欢
  • 2021-05-22
  • 2017-12-05
  • 1970-01-01
  • 2011-09-10
  • 2011-06-24
  • 2016-10-02
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多