be.bittich.quote.controller.impl.DefaultExceptionHandler.java Source code

Java tutorial

Introduction

Here is the source code for be.bittich.quote.controller.impl.DefaultExceptionHandler.java

Source

/*
 * Copyright 2014 nateriver.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package be.bittich.quote.controller.impl;

import static be.bittich.quote.core.Constant.APPLICATION_JSON;
import static com.google.common.collect.Maps.newHashMap;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 *
 * @author nateriver
 */
@ControllerAdvice
public class DefaultExceptionHandler implements Serializable {

    private static final long serialVersionUID = -7454200256619442642L;

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler({ MissingServletRequestParameterException.class,
            UnsatisfiedServletRequestParameterException.class, HttpRequestMethodNotSupportedException.class,
            ServletRequestBindingException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public @ResponseBody Map<String, Object> handleRequestException(Exception ex) {
        Map<String, Object> map = newHashMap();
        map.put("error", "Request Error");
        map.put("cause", ex.getMessage());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public @ResponseBody Map<String, Object> handleValidationException(ConstraintViolationException ex)
            throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Validation Failure");
        map.put("violations", convertConstraintViolation(ex.getConstraintViolations()));
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public @ResponseBody Map<String, Object> handleValidationException(MethodArgumentNotValidException ex)
            throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Validation Failure");
        map.put("violations", convertConstraintViolation(ex));
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(ObjectRetrievalFailureException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public @ResponseBody Map<String, Object> handleValidationException(ObjectRetrievalFailureException ex)
            throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Entity Not Found");
        map.put("cause", ex.getMessage());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public @ResponseBody Map<String, Object> handleDataIntegrityViolationException(
            DataIntegrityViolationException ex) throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Data Integrity Error");
        map.put("cause", ex.getCause().getLocalizedMessage());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(DataAccessException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody Map<String, Object> handleDataAccessException(DataAccessException ex) throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Data Error");
        map.put("cause", ex.getCause().getMessage());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public @ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(
            HttpMediaTypeNotSupportedException ex) throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Unsupported Media Type");
        map.put("cause", ex.getLocalizedMessage());
        map.put("supported", ex.getSupportedMediaTypes());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public @ResponseBody Map<String, Object> handleDuplicateKeyException(DuplicateKeyException ex)
            throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Duplicate Key Exception");
        map.put("cause", ex.getLocalizedMessage());
        map.put("supported", ex.getMessage());
        return map;
    }

    @RequestMapping(produces = APPLICATION_JSON)
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody Map<String, Object> handleUncaughtException(Exception ex) throws IOException {
        Map<String, Object> map = newHashMap();
        map.put("error", "Unknown Error");
        if (ex.getCause() != null) {
            map.put("cause", ex.getCause().getMessage());
        } else {
            map.put("cause", ex.getMessage());
        }
        return map;
    }

    private Map<String, Map<String, Object>> convertConstraintViolation(
            Set<ConstraintViolation<?>> constraintViolations) {
        Map<String, Map<String, Object>> result = newHashMap();
        constraintViolations.stream().forEach((constraintViolation) -> {
            Map<String, Object> violationMap = newHashMap();
            violationMap.put("value", constraintViolation.getInvalidValue());
            violationMap.put("type", constraintViolation.getRootBeanClass());
            violationMap.put("message", constraintViolation.getMessage());
            result.put(constraintViolation.getPropertyPath().toString(), violationMap);
        });
        return result;
    }

    private Map<String, Map<String, Object>> convertConstraintViolation(MethodArgumentNotValidException ex) {
        Map<String, Map<String, Object>> result = newHashMap();
        ex.getBindingResult().getAllErrors().stream().forEach((error) -> {
            Map<String, Object> violationMap = newHashMap();
            violationMap.put("target", ex.getBindingResult().getTarget());
            violationMap.put("type", ex.getBindingResult().getTarget().getClass());
            violationMap.put("message", error.getDefaultMessage());
            result.put(error.getObjectName(), violationMap);
        });
        return result;
    }

}