java - 如何处理 RESTful Spring MVC Controller 中的验证错误和异常?

标签 java spring rest spring-mvc

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

@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;
    }
}

最佳答案

出错就抛异常,然后用@ExceptionHandler to annotate another method然后它将处理异常并呈现适当的响应。

关于java - 如何处理 RESTful Spring MVC Controller 中的验证错误和异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245487/

相关文章:

spring - 为什么mockMVC和mockito不能一起工作?

java - 如何有效地使用 Spring 的 JDBCTemplate 执行 IN() SQL 查询?

java - java中int变量的08和8之间的区别

java - 将默认bean构造函数设置为public在spring中不会实例化

java - 使用 @Scope ("prototype"从单例更改为原型(prototype))

ios - 从 ios5 应用程序与 REST 服务通信

sql-server - 将nodejs Rest api连接到Azure SQL Server

Java-netbeans : Cannot run program "${platforms. default_platform.home}\bin\java

java - 如何确定JNI(jogl)在运行时是否可用?

java - 用户 token 认证 Spring MVC RESTful API