【问题标题】:throw different exception when catch DataIntegrityViolationException捕获 DataIntegrityViolationException 时抛出不同的异常
【发布时间】:2018-03-10 09:17:24
【问题描述】:

我正在使用 spring mvc,来处理我使用全局异常处理程序的异常

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
    @ExceptionHandler({DataIntegrityViolationException.class})
    public @ResponseBody AdminResponse handleConflict(DataIntegrityViolationException ex,HttpServletResponse httpServletResponse) {

        AdminResponse error = new AdminResponse ();

        error.setStatus(Status.FAILURE);
        error.setErrorDescription(ex.getMessage());

        return error;
    }

Spring 处理捕捉DataIntegrityViolationException,但我需要扩展DataIntegrityViolationException,同时我不能强制Spring 捕捉我的自定义异常。 捕获DataIntegrityViolationException时如何告诉Spring抛出我的自定义异常@

【问题讨论】:

  • throw ?!
  • @Oleg ,我需要的是让 Spring 处理它,每当 Spring 捕获 DataIntegrityViolationException 时,它应该抛出我的自定义异常。
  • 对不起,我不明白,throw 随便你的handleConflict 方法。
  • @Oleg,在 Spring 中我们不使用 try 和 catch 来捕获异常,Spring 框架具有 ControllerAdvice 注解功能,可以捕获某种异常,无需开发人员代码。现在 Spring 可以捕获 DataIntegrityViolationException,我需要的是当 Spring 捕获 DataIntegrityViolationException 我希望 Spring 抛出并处理另一个(我的异常)异常。
  • 无论如何,祝你好运。

标签: java spring spring-mvc exception-handling


【解决方案1】:

我的示例代码。这是commonExceptionHandler。 您使用“抛出异常”您的服务和 dao 层。春天处理你的异常。

@ExceptionHandler(value = { Exception.class, SQLException.class })
public @ResponseBody String checkDefaultException(HttpServletRequest req, Exception exception,
        HttpServletResponse resp) throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    CommonExceptionModel model = new CommonExceptionModel();

    model.setMessage("InternalServerError");
    model.setCode(HttpStatus.INTERNAL_SERVER_ERROR.toString());

    String commonExceptionString = mapper.writeValueAsString(model);

    logger.error(commonExceptionString + " exception : " + exception);

    return commonExceptionString;
}

您的错误参考:enter link description here

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2013-06-24
    • 2011-08-24
    • 1970-01-01
    • 2013-04-14
    • 2020-10-03
    • 1970-01-01
    • 2012-04-26
    相关资源
    最近更新 更多