如何在RestTemplate中获取自定义@ControllerAdvice异常?

时间:2017-05-17 09:14:58

标签: spring rest exception

我正在使用@ControllerAdvice从我的休息服务中抛出一个自定义异常:

@ControllerAdvice
public class ExceptionTranslator {

    @ExceptionHandler(PersonNotFoundException.class)
    public void handlePersonNotFoundException(PersonNotFoundException ex, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "The requested person: '" + ex.getId() + "' was not found");
     }

    @ExceptionHandler(NonExistingPersonException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public PersonNotFoundExceptionVM handlePersonNotFoundException(NonExistingPersonException ex) {
         return new PersonNotFoundExceptionVM(ErrorConstants.PERSON_DOES_NOT_EXIST, "The person with id '" + ex.getId() + "' does not exist");
    }

    @ExceptionHandler(ForbiddenException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public ForbiddenExceptionVM handleForbiddenException(ForbiddenException ex){
      return new ForbiddenExceptionVM(ErrorConstants.ACCESS_FORBIDDEN, ex.getExtraInfo(), 3);
    }
  }

使用RestTemplate调用服务时,有没有办法接收我的PersonNotFoundExceptionVM自定义异常对象?我知道我可以在RestTemplate上使用CustomResponseErrorHandler,但在那里我只能访问ClientHttpResponse返回的主体。我是否必须解析正文以获取PersonNotFoundExceptionVM字段?处理REST服务错误的最佳实践是什么?

0 个答案:

没有答案