Spring: GlobalExceptionHandling
package com.aptito.kkm.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.rest.webmvc.support.ExceptionMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@ControllerAdvice
public class GlobalExceptionHandling {
@ExceptionHandler({ Exception.class })
@ResponseBody
public ResponseEntity<?> handleAnyException(final Exception e) {
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler({ DataIntegrityViolationException.class, SQLIntegrityConstraintViolationException.class })
@ResponseBody
public ResponseEntity<?> handleConflictException(final Exception e) {
return errorResponse(e, HttpStatus.CONFLICT);
}
// -=Security=-
// @ExceptionHandler({ InvalidKeyException.class, NoSuchAlgorithmException.class })
// @ResponseBody
// public ResponseEntity<?> handleHashException(final Exception e) {
// return errorResponse(new Exception("Encrypt/Decrypt key is requested"), HttpStatus.LOCKED);
// }
// @ExceptionHandler({ IOException.class, ParseException.class, ProcessingException.class, JsonParseException.class,
// JsonMappingException.class })
@ExceptionHandler({ IOException.class, JsonParseException.class, JsonMappingException.class })
@ResponseBody
public ResponseEntity<?> handleParseException(final Exception e) {
return errorResponse(e, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ SQLException.class, DataAccessException.class, RuntimeException.class })
@ResponseBody
public ResponseEntity<?> handleSQLException(final Exception e) {
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ResponseBody
public ResponseEntity<?> handleUnauthenticationException(final Exception e) {
return errorResponse(e, HttpStatus.BAD_REQUEST);
}
protected ResponseEntity<ExceptionMessage> errorResponse(final Throwable throwable, final HttpStatus status) {
if (null != throwable) {
return response(new ExceptionMessage(throwable), status);
} else {
return response(null, status);
}
}
protected <T> ResponseEntity<T> response(final T body, final HttpStatus status) {
return new ResponseEntity<T>(body, status);
}
}