@exceptionhandler 在 Spring REST 中不工作

@exceptionhandler not working in Spring REST

我是 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。为什么会发生这种行为?

请关注我的 on exception handling. I've created sample project for more detailed reference which can found here

试试这个

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;
    }
}