【发布时间】:2020-10-13 17:42:41
【问题描述】:
我正在为用户开发一个 Spring Boot Web 应用程序,其中一项功能是让用户能够重置他们的密码。为此,他们必须提供他们的电子邮件地址,并向他们发送验证消息,以便他们能够重置密码。不过,我的问题是如何针对用户提供的电子邮件在数据库中不存在的情况发出错误消息?到目前为止,我的 GlobalExceptionHandler.java 如下:
package bcoreHW.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class GlobalExceptionHandler {
@Value("${message.error.exception}")
private String exceptionMessage;
@Value("${message.user.nonexistent}")
private String userNonexistentMessage;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler(value=Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.getModel().put("message", exceptionMessage);
modelAndView.getModel().put("url", req.getRequestURL());
modelAndView.getModel().put("exception", e);
modelAndView.setViewName("app.exception");
return modelAndView;
}
}
所以我现在得到的错误是基本的 404 HttpStatus.NOT_FOUND 错误,我只是说“发生错误”。但当然我希望这个更具体,以便用户了解更多问题,并且 userNonexistentMessage 会说“此用户不存在。”
那么,如何为这种情况添加异常处理程序?谢谢!
【问题讨论】:
标签: java spring-boot spring-mvc exception