2016-11-30 112 views
0

我要处理这个异常:如何用Spring/JPA处理异常?

try { 
     save = usersRepository.save(user); 
} 
catch (Exception gottaCatchEmAll){ 
     System.out.println("got it"); 
} 

在日志中我看到:

不能添加或更新子行,外键约束失败

我怎么能赶上它?

回答

1

我会建议编写建议处理程序类来处理任何异常。例如,我假设你的例外类型是DataIntegrityViolationException。这将被包裹在某种DTO中,可以返回到前端或做你喜欢的东西。

@ControllerAdvice 
public class ExceptionHandler { 

    @ExceptionHandler(DataIntegrityViolationException.class) 
    @ResponseStatus(HttpStatus.BAD_REQUEST) 
    @ResponseBody 
    public ErrorDto processConstraintError(DataIntegrityViolationException ex) { 
    return new ErrorDto(ex.getMessage()); 
    } 

} 

不需要尝试从JPA中捕捉任何东西。

+0

我把这个添加到我的项目中没有任何事情发生,如何激活它为特定的控制器? – user3871754

+0

除非您在建议注释中指定'basePackages',否则它不绑定到特定的控制器。你需要显示你的Spring配置在哪里扫描这个包。 – Vaelyr

+0

在启动时我在日志中看到:寻找ControllerAdvice :: ExceptionHandler中检测到ExceptionHandler方法,我使用spring引导+ spring安全性,我没有任何额外的配置spring.jpa.show-sql = true – user3871754