@exceptionhandler在Spring REST中不起作用

时间:2018-07-02 08:30:40

标签: java spring spring-mvc spring-restcontroller

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

@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一起工作。为什么会发生这种情况?

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

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