【发布时间】: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<String> handleCountryNotFound(CountryNotFoundException e){ return ResponseEntity.status(404).entity("not found").build()}然后看看有没有被调用/捕获? -
您是否定义了
CountryNotFoundException来扩展Exception? -
@DforTye 不,它扩展了 RuntimeException..
标签: java spring spring-mvc spring-restcontroller