如何在RESTful Spring MVC控制器中处理验证错误和异常? [英] How to handle validation errors and exceptions in a RESTful Spring MVC controller?

查看:99
本文介绍了如何在RESTful Spring MVC控制器中处理验证错误和异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何在此控制器操作方法中处理验证错误和可能的异常:

@RequestMapping(method = POST)
@ResponseBody
public FooDto create(@Valid FooDTO fooDto, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return null; // what to do here?
                     // how to let the client know something has gone wrong?
    } else {
        fooDao.insertFoo(fooDto); // What to do if an exception gets thrown here?
                                  // What to send back to the client?
        return fooDto;
    }
}

解决方案

如果有错误,请引发异常,然后使用 解决方案

Throw an exception if you have an error, and then use @ExceptionHandler to annotate another method which will then handle the exception and render the appropriate response.

这篇关于如何在RESTful Spring MVC控制器中处理验证错误和异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆