我正在开发Spring 3.2& Hibernate 3.6,任何人都可以解释如何在Sping MVC&中解决异常问题. Hibernate …我只是分享示例代码.
控制器层
public Integer saveEployee(HttpServletRequest req,HttpServletResponse res){
Employee empObj = new Employee();
empObj.setName(req.getParameter("empName"));
......................
......................
Integer empId = materService.saveEmployee(empObj);
return empId;
}
服务层
public Integer saveEmployee(Employee empObj){
return masterDao.saveEmployee(empObj);
}
DAO层
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异常或任何用户定义的异常等.
那么什么是最佳实践或如何同时处理Controller,Service和DAO Layer中的异常.
处理spring-mvc应用程序中的异常的一种方法是在适当的情况下使用您自己的库来包装底层库中的致命错误,以它们被抛出的级别命名,例如: ServiceException或RepositoryException.然后,@ ControllerAdvice-annotated类可以使用@ ErrorHandler-annotated方法处理这些错误并返回5XX http错误.
常见的应用程序错误,例如由于ID不正确而未找到的实体,可能会导致自定义异常,例如:引发NotFoundException并随后在@ ControllerAdvice-annotated类中捕获.
这种技术的优点是,您可以在不同的应用程序层中使用较少的错误处理代码,并可以集中将异常转换为响应.
示例@ ControllerAdvice-annotated类:
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({NotFoundException.class})
protected ResponseEntity
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。