Skip to main content

Exception Handilng

Pada artikel ini kita akan membahas tentang apa itu Exception Handling dalam Java.

Standardisasi Exception Handling​

terdapat beberapa standar yang di gunakan oleh aplikasi java yaitu sebagai berikut \ untuk error code yang di gunakan adalah sebagai berikut :

  • 400 : Bad Request
  • 401 : Unauthorized
  • 403 : Forbidden
  • 404 : Not Found
  • 500 : Internal Server Error
  • 551 : JDBC Connection Exception
  • 552 : Redis Connection Failure Exception
  • 553 : Process Engine Exception
  • 554 : Api Exception

Implementasi Exception Handling​

Untuk mengimplementasikan error handling pada aplikasi java kita dapat menggunakan anotasi @ExceptionHandler yang di sediakan oleh spring framework.

@ExceptionHandler({AlurKerjaException.class})
public ResponseEntity<Object> alurKerjaException(HttpServletRequest request,
AlurKerjaException ex){

String lang = request.getAttribute("lang") != null ? request.getAttribute("lang").toString() : ID;
ResourceBundle message = ResourceBundle.getBundle(MESSAGES, lang.equals(ID) ? Locale.ROOT : Locale.ENGLISH);

String text = message.getString(ex.getMessage());
if (ex.getValues() != null){
int i = 0;
for (String value : ex.getValues()) {
text = text.replace("{" + i + "}", value);
i++;
}
}

if (ex.getCode() == 400)
return badRequest(null, text);
else if (ex.getCode() == 404)
return notFound(null, text);
else if (ex.getCode() == 403)
return forbidden(null, text);
else if (ex.getCode() == 401)
return error(HttpStatus.UNAUTHORIZED, text);
return error(HttpStatus.INTERNAL_SERVER_ERROR, text);
}

@ExceptionHandler({JDBCConnectionException.class})
public ResponseEntity<Object> jDBCConnectionException(HttpServletRequest request, JDBCConnectionException ex){
return ResponseEntity.status(551).body(new CommonRs(551, ex.getMessage(), ex));
}

@ExceptionHandler({SQLException.class})
public ResponseEntity<Object> sQLException(HttpServletRequest request, SQLException ex){
return ResponseEntity.status(551).body(new CommonRs(551, ex.getMessage(), ex));
}

@ExceptionHandler({RedisConnectionFailureException.class})
public ResponseEntity<Object> redisConnectionFailureException(HttpServletRequest request, RedisConnectionFailureException ex){
return ResponseEntity.status(552).body(new CommonRs(552, ex.getMessage(), ex));
}

@ExceptionHandler({JedisException.class})
public ResponseEntity<Object> jedisException(HttpServletRequest request, JedisException ex){
return ResponseEntity.status(552).body(new CommonRs(552, ex.getMessage(), ex));
}

@ExceptionHandler({ProcessEngineException.class})
public ResponseEntity<Object> processEngineException(HttpServletRequest request, ProcessEngineException ex){
return ResponseEntity.status(553).body(new CommonRs(553, ex.getMessage(), ex));
}

@ExceptionHandler({ApiException.class})
public ResponseEntity<Object> apiException(HttpServletRequest request, ApiException ex){
return ResponseEntity.status(554).body(new CommonRs(554, ex.getMessage(), ex));
}