捕获DataIntegrityViolationException时抛出不同的异常

时间:2017-09-28 14:59:34

标签: java spring spring-mvc exception-handling

我使用spring mvc,处理excpetion我使用全局异常处理程序

@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抛出我的自定义异常

1 个答案:

答案 0 :(得分:0)

enter image description here

我的示例代码。这是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