SpringブートでREST APIを構築しており、DAOレイヤーがHibernateで実装されています。アプリケーションで例外をスローして処理する正しい方法を理解する必要があります。このようHibernateを使用したSpringブートアプリケーションの例外処理
@Repository
public class UserDaoImpl
{
public getAllUsers() throws Exception
{
//get All Users from DB
}
}
@Service
public class UserServiceImpl
{
public getAllUsers throws MyCustomException
{ try{
userDaoImpl.getAllUsers();
}
catch(Exception e)
{
throw MyCustomException();
}
}
}
と例外マッパーで
@ControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({MyCustomException.class})
@ResponseBody
public ResponseEntity<?> handleCustomException(Exception e) {
log.error("", e);
Map<String, String> error = new HashMap<String, String>();
error.put("message", e.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_ACCEPTABLE, MessageResource.getLogMessage("BAD_REQUEST_EXCEPTION"));
}
}
public class MyCustomException extends RuntimeException
{
///// ....
}
だから私は追加したが、サービスレイヤでDAO層とキャッチで句を(例外をスロー)スローし、カスタム例外(チェックされない例外)でそれをラップしてみませんかコントローラーレイヤーで例外を宣言しないでください。 これが正しいですか?またはいくつかのより良い方法がありますか?