java - 从 Spring REST Web 服务以 JSON/XML 形式抛出异常

标签 java spring web-services rest exception

我有一个如下所示的 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/

相关文章:

java - 从 Windows 使用 wsimport - url = http ://www. webservicex.net/geoipservice.asmx?WSDL

java - 如何配置过滤器在 servlet 处理后工作?

java - OpenLDAP 仅返回密码过期的警告

java - 使用 Java 在 Jersey 上通过 REST 提供多个文件列表

java - 刷新引起的延迟初始化错误

spring - 无法在可访问已部署 JAR 的 Wildfly 中加载 Spring 框架库

c# - 如何使用 SOAP V2 为 Magento 设置自定义 api?

java - 具有分页、排序和规范的 JPA

java - pom为3个应用程序使用Spring-mvc的公共(public)依赖

java - 当父类(super class)没有构造函数时,如何在子类中声明构造函数