我正在开发Spring 3.2& Hibernate 3.6,任何人都可以解释如何在Sping MVC&中解决异常问题. Hibernate …我只是分享示例代码.@H_301_2@
控制器层@H_301_2@
@H_301_2@
public Integer saveEployee(HttpServletRequest req,HttpServletResponse res){
Employee empObj = new Employee();
empObj.setName(req.getParameter("empName"));
......................
......................
Integer empId = materService.saveEmployee(empObj);
return empId;
}
服务层@H_301_2@
@H_301_2@
public Integer saveEmployee(Employee empObj){
return masterDao.saveEmployee(empObj);
}
DAO层@H_301_2@
@H_301_2@
public Integer saveEmployee(Employee empObj){
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Integer empId = session.save(empObj);
tx.commit();
session.close();
return empId;
}
>现在假设在DAO层发生任何异常,同时保存empObj,如d / b关闭或连接失败或发生任何其他类型的休眠异常,如ConstraintViolationException或IntegrityConstraintViolationException等.
>如果有可能在控制器层处理NullPointerException等java异常或任何用户定义的异常等.@H_301_2@
那么什么是最佳实践或如何同时处理Controller,Service和DAO Layer中的异常.
处理spring-mvc应用程序中的异常的一种方法是在适当的情况下使用您自己的库来包装底层库中的致命错误,以它们被抛出的级别命名,例如: ServiceException或RepositoryException.然后,@ ControllerAdvice-annotated类可以使用@ ErrorHandler-annotated方法处理这些错误并返回5XX http错误.@H_301_2@
常见的应用程序错误,例如由于ID不正确而未找到的实体,可能会导致自定义异常,例如:引发NotFoundException并随后在@ ControllerAdvice-annotated类中捕获.@H_301_2@
这种技术的优点是,您可以在不同的应用程序层中使用较少的错误处理代码,并可以集中将异常转换为响应.@H_301_2@
示例@ ControllerAdvice-annotated类:@H_301_2@
@H_301_2@
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({NotFoundException.class})
protected ResponseEntity