我有一个如下所示的 REST Web 服务 Controller :
@RequestMapping(value = URIConstants.URL_DOCUMENT_SEARCH, method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
protected DocumentSearchResponse getDocuments(@Valid @ModelAttribute DocumentSearchRequest objDMSRequest,BindingResult bindingResult, HttpServletRequest objServletRequest) throws AppException
{
if (bindingResult.hasErrors())
{
//I want to throw my custom exception here
///Or can anyone suggest a more clean and efficient way
}
-----More code and logic
}
我有一个自定义异常和处理程序,它们将抛出无效的 HTTP 无效请求异常。自定义异常有错误代码和错误描述字段。 我的要求是有一种方法可以将绑定(bind)结果中的错误解析为自定义异常并将其放入 Controller 中。
最佳答案
你可以做什么:
return new ResponseEntity<String>(errorDescription,HttpStatus.BAD_REQUEST);
或者,如果你真的想使用异常,你可以硬核(不推荐):
try {
throw new CustomException();
} catch(CustomException e) {
e.printStackTrace();
return new ResponseEntity<String>(e.getErrorDescription(),e.getStatusCode());
}
顺便说一句:返回异常不好,这就是我不显示它的原因。
关于java - 从 Spring REST Web 服务以 JSON/XML 形式抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30251431/