从 Spring REST 网络服务中抛出异常 JSON/XML

Throwing exceptions from Spring REST webservice as JSON/XML

我有一个 REST 网络服务控制器,如下所示:

@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 无效请求异常。自定义异常有错误代码和错误描述字段。 我的要求是有没有一种方法可以将绑定结果中的错误解析为客户异常并将其放入控制器中。

你能做什么:

return new ResponseEntity<String>(errorDescription,HttpStatus.BAD_REQUEST);

或者,如果你真的想使用Exception(不推荐),你可以硬核:

try {
   throw new CustomException();
} catch(CustomException e) {
  e.printStackTrace();
  return new ResponseEntity<String>(e.getErrorDescription(),e.getStatusCode());
}

顺便说一句:返回异常不好,这就是我不显示它的原因。

就这么简单 1. 创建一个扩展 Exception.

的 class
 class MyCustomException extends Exception{
     MyCustomException(){
     }
     MyCustomException(Object e){
         super(e)
     }
 }

2。让你的代码抛出相同类型的异常

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(method=RequestMethod.POST)
    public ResponseEntity create(@Valid User user, BindingResult bindingResult) {
        try{
            if (bindingResult.hasErrors()) {
                throw new MyCustomException();
            }
        } catch(MyCustomException e){
            //do what ever you want to do with it
        }
        ...
}

3。伙计,你已经完成了......:)

@Albert-Pinto 首先,您尝试这样做的方式是完全错误的。如果你想消费一个对象,它应该以@RequestBody 的形式出现,而不仅仅是一个简单的对象。您在示例中所做的是我们处理 Web 应用程序的 MVC 方式,而不是我们处理 Web 服务的方式。所以上面的代码将变成

@Controller 
@RequestMapping("/user")
 public class UserController {
   @RequestMapping(method=RequestMethod.POST)
   public ResponseEntity create(@RequestBody User user) {
   try {
       throw new CustomException();
    } catch(CustomException e) {
       e.printStackTrace();
       return new ResponseEntity<String>(e.getErrorDescription(),e.getStatusCode());
    }
}