【问题标题】:How to handle repository exception in the controller - spring mvc如何处理控制器中的存储库异常-spring mvc
【发布时间】:2015-09-22 12:42:55
【问题描述】:

我正在使用弹簧靴和弹簧 MVC。我正在创建一个简单的表单(CRUD) 这是代码:

@Document
public class User
{
    @Id
    private ObjectId id;
    @Indexed(unique=true)
    @NotNull
    @Size(min=2, max=30)
    private String username;
    @NotNull
    @Size(min=2, max=30)
    private String password;
    private List<String> roles;
    ...

控制器:

@Controller
@RequestMapping("/admin")
public class AdminController {
    ...
    /**
     * NEW USER (POST)
     */
    @RequestMapping(value = "new", method = RequestMethod.POST)
    public ModelAndView newUser(@Valid User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return new ModelAndView("/admin/new");
        }
        user.setRoles(Arrays.asList(Constants.ROLE_ADMIN));
        ur.save(user);
        return new ModelAndView("redirect:/admin");
    }
    /**
     * NEW USER (VIEW)
     */
    @RequestMapping(value = "new", method = RequestMethod.GET)
    public ModelAndView newUser(User user) {
        ModelAndView mv = new ModelAndView("admin/new");
        return mv;
    }
    ...
}

和视图:

<form name="new" th:action="@{/admin/new}" th:object="${user}" method="post">
        <table>
            <tr th:if="${error != null}">
                <td colspan="4">
                    <span th:text="${error}"></span>
                </td>
            </tr>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="username" autocomplete="off"/></td>
                <td width="10"/>
                <td th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" autocomplete="off"/></td>
                <td width="10"/>
                <td th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></td>
            </tr>
            <tr>
                <td><button type="submit">Create</button></td>
            </tr>
        </table>
    </form>

如果我输入的用户名大于 30 个字符,它就可以工作。

但是如果我从存储库中获得异常,例如: 来自 mongodb 存储库的 DuplicateKey 无效。

所以我试着把这段代码放在控制器中:

@ExceptionHandler(Exception.class)
public ModelAndView handleCustomException(Exception ex) {
    ModelAndView model = new ModelAndView("admin/new");
    model.addObject("error", ex.getMessage());
    return model;

}

它处理所有异常,但此时我没有“用户”或“绑定结果”,当它尝试渲染时出现此错误:

2015-09-22 13:36:55.498 ERROR 6208 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('username')" (admin/new:21)] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute 

我做错了什么? 我应该如何处理这种异常? 有没有办法将 USER 发送到 ExceptionHandler?

谢谢。

【问题讨论】:

    标签: spring mongodb spring-mvc exception thymeleaf


    【解决方案1】:

    因为您不必从错误处理程序返回 admin/new。该视图期待您在普通控制器中正确填充的用户对象。如果发生错误,这个对象根本不存在。因此,从错误控制器返回另一个视图:例如ModelAndView model = new ModelAndView("admin/error");

    无论如何,这不是解决方案。您需要捕获异常。在这种情况下,最好有一个称为服务的中间层。在服务中,您可以捕获任何存储库异常并决定如何处理它们。

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 1970-01-01
      • 2016-10-14
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多