argos/dmp-backend/web/src/main/java/eu/eudat/controllers/controllerhandler/ControllerErrorHandler.java

48 lines
1.8 KiB
Java
Raw Normal View History

2017-12-23 16:56:05 +01:00
package eu.eudat.controllers.controllerhandler;
2018-06-27 12:29:21 +02:00
import eu.eudat.core.logger.Logger;
import eu.eudat.core.models.exception.ApiExceptionLoggingModel;
2018-08-31 16:12:31 +02:00
import eu.eudat.models.data.helpers.responses.ResponseItem;
2018-06-27 12:29:21 +02:00
import eu.eudat.models.data.security.Principal;
2018-08-31 16:12:31 +02:00
import eu.eudat.types.ApiMessageCode;
2017-12-23 16:56:05 +01:00
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
2018-06-27 12:29:21 +02:00
import types.LoggingType;
2017-12-23 16:56:05 +01:00
2018-06-27 12:29:21 +02:00
import java.util.HashMap;
import java.util.Map;
2018-02-01 10:08:06 +01:00
2018-06-27 12:29:21 +02:00
/**
* Created by ikalyvas on 6/12/2018.
*/
2017-12-23 16:56:05 +01:00
@ControllerAdvice
public class ControllerErrorHandler {
2018-06-27 12:29:21 +02:00
private Logger logger;
2017-12-23 16:56:05 +01:00
@Autowired
2018-06-27 12:29:21 +02:00
public ControllerErrorHandler(Logger logger) {
this.logger = logger;
2017-12-23 16:56:05 +01:00
}
2018-08-31 16:12:31 +02:00
@ExceptionHandler(NullPointerException.class)
2017-12-23 16:56:05 +01:00
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
2018-08-31 16:12:31 +02:00
public ResponseItem<Exception> processValidationError(Principal principal, Exception ex) throws Exception {
2018-06-27 12:29:21 +02:00
ApiExceptionLoggingModel<Exception, Principal> apiExceptionLoggingModel = new ApiExceptionLoggingModel<>();
apiExceptionLoggingModel.setCode(HttpStatus.BAD_REQUEST);
apiExceptionLoggingModel.setUser(principal);
2018-08-31 16:12:31 +02:00
Map<String, Exception> exceptionMap = new HashMap<>();
exceptionMap.put("exception", ex);
2018-06-27 12:29:21 +02:00
apiExceptionLoggingModel.setData(exceptionMap);
apiExceptionLoggingModel.setMessage(ex.getMessage());
apiExceptionLoggingModel.setType(LoggingType.ERROR);
this.logger.error(apiExceptionLoggingModel);
2018-08-31 16:12:31 +02:00
return new ResponseItem<Exception>().message(ex.getMessage()).status(ApiMessageCode.DEFAULT_ERROR_MESSAGE);
2017-12-23 16:56:05 +01:00
}
}