2

我在使用 Spring 和 Jackson 生成正确的错误消息时遇到问题。场景:具有自定义模型的控制器@ResponseBody(见下文)具有两个属性的模型,这可能会导致解析错误。Date现在,如果这些字段的解析失败(例如,得到一个无效的字符串 a ),我想返回一个正确的错误消息。

如果发生解析错误,Spring 将捕获它并返回400 Bad Request带有 HTML 正文的响应。虽然我能够实现自己的HandlerExceptionResolver,但它会捕获这种异常以生成有意义的错误消息。不幸的是,我只能捕捉到第一个解析错误,而不是可能的第二个。

那么,有没有办法收集所有解析/反序列化错误并生成包含所有问题的正确错误消息?

我正在使用 Jackson 1.7.1 和 Spring 3.2.2。


一些示例代码:

时间控制器.java

@Controller
@RequestMapping("/time")
public class TimeController {
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    TimeDocument create(@RequestBody TimeDocument entity) {
        // magic
        return entity;
    }
}

时间文档.java

public class TimeDocument {
    public String name;
    public Date date1;
    public Date date2;
}

请求 1:我会得到一个200 OK.

{
  "name": "test",
  "date1": 123,
  "date2": 1234
}

请求 2:我将得到一个400 Bad Request,但我能够生成正确的错误消息,例如:“日期 1 的格式无效。”。

{
  "name": "test",
  "date1": "crap",
  "date2": 1234
}

请求 3:我会得到一个400 Bad Request,但我无法生成正确的错误消息,例如:“日期 1 的格式无效。日期 2 的格式无效。”。

{
  "name": "test",
  "date1": "crap",
  "date2": "crap"
}
4

1 回答 1

0

好吧,我认为您最好需要使用或仅使用插件在客户端Spring MVC Form Validation验证值(我只是假设您因为使用而使用)。inputjquery.validatejQuery@ResponseBody

否则,我想到的另一个解决方案是实现这样的东西:

(首先,在您的调用中添加一个getterandsetter来存储验证结果)。fieldentitymessage

然后:

@Controller
@RequestMapping("/time")
public class TimeController {
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody String create(@RequestBody TimeDocument entity) {

        String json = null;        

        try {

            //1. Create 'jackson' object mapper
            ObjectMapper objectMapper = new ObjectMapper();  

            //2. Capture data from your entity
            String name = entity.getName();
            Date date1 = entity.getDate1();
            Date date2 = entity.getDate2();

            //3. Validate 'name', 'date1', 'date2' with some regex (a possibility) or any method you want.

            //4. Suppossing that you implemented a method like this to validate your 'bean' or 'dto' that returns 'boolean'
            if(!validate(entity)) {

               //5. If everything is not according to your validation rules, set a message to your entity.
               entity.setMessage("There was an error in the input values.");
            }

            //6. Convert your 'bean' or 'dto' as 'json' string
            json = objectMapper.writeValueAsString(entity);            

        } catch (Exception ex) {
            //handle the Exception
        }

        return json;
    }
}

现在,在客户端(假设您正在使用jQuery ajax或只是$.post)。

在 中执行以下操作callback

(..), function(data) {
   if(data != null) { //Callback is not null

      //Parse the 'String' result from 'Controller' as 'JSON' from 'Jackson'
      var obj = $.parseJSON(data);

      if(obj.message != '') {
         alert(obj.message) //An error ocurred in the validation.
      } else {
         //Show the data
         alert('Name: ' + obj.name + ' Date1: ' + obj.date1 + ' Date2: ' + obj.date2);
      }
   }
});

因此,如果 中没有message现在,则entity意味着没有error现在。我会建议这一点,并考虑我在第一行中写的内容,以便在旁边进行非常好的client验证server

于 2013-07-04T22:46:51.693 回答