Nav*_*een 8 java spring hibernate exception
我正在开发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;
}
Run Code Online (Sandbox Code Playgroud)
服务层
public Integer saveEmployee(Employee empObj){
return masterDao.saveEmployee(empObj);
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
现在假设任何异常发生在DAO层,同时节省了empObj像d/B了下来或连接失败或任何其他类型的Hibernate异常发生类似ConstraintViolationException或IntegrityConstraintViolationException等.
如果有可能NullPointerException在控制器层处理java异常或任何用户定义的异常等.
那么什么是最佳实践或如何同时处理Controller,Service和DAO Layer中的异常.
您不会同时处理应用程序所有级别的异常;您必须考虑它们的上下文含义以及适合您的应用程序的策略。有些错误应该被忽略,有些应该被包裹,有些应该允许直接引发。
在spring-mvc应用程序中处理异常的一种方法是在适当的情况下用您自己的库包装来自底层库的致命错误,以它们被抛出的级别命名,例如ServiceException或RepositoryException。一@ControllerAdvice则-annotated类可以处理这些错误@ErrorHandler-annotated方法和返回5XXHTTP错误。
常见的应用程序错误,例如由于不正确而未找到实体id可能会导致自定义异常,例如NotFoundException引发并随后在您的@ControllerAdvice-annotated 类中捕获。
这种技术的优点是您在不同的应用程序层中有更少的错误处理代码,并且可以集中将异常转换为响应。
一个带@ControllerAdvice注释的示例类:
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({NotFoundException.class})
protected ResponseEntity<Object> handleNotFound(RuntimeException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(),
null,
HttpStatus.NOT_FOUND, request);
}
@ExceptionHandler({ServiceException.class, RepositoryException.class})
protected ResponseEntity<Object> handleInternalError(RuntimeException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(),
null,
HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}
Run Code Online (Sandbox Code Playgroud)
根据我在新项目中的经验,
因此在控制器层处理事务。
| 归档时间: |
|
| 查看次数: |
11385 次 |
| 最近记录: |