org.apigw.authserver.web.admin.DefaultAdminExceptionHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.apigw.authserver.web.admin.DefaultAdminExceptionHandler.java

Source

/**
 *   Copyright 2013 Stockholm County Council
 *
 *   This file is part of APIGW
 *
 *   APIGW is free software; you can redistribute it and/or modify
 *   it under the terms of version 2.1 of the GNU Lesser General Public
 *   License as published by the Free Software Foundation.
 *
 *   APIGW is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with APIGW; if not, write to the
 *   Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 *   Boston, MA 02111-1307  USA
 *
 */
package org.apigw.authserver.web.admin;

import com.google.common.collect.Maps;
import org.apigw.authserver.web.admin.v1.dto.ValidationErrorDTO;
import org.apigw.authserver.web.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
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;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

@ControllerAdvice(basePackages = { "org.apigw.authserver.web.admin.v1.controller" })
public class DefaultAdminExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultAdminExceptionHandler.class);

    //    private MessageSource messageSource;
    //
    //    @Autowired
    //    public DefaultAdminExceptionHandler(MessageSource messageSource) {
    //        this.messageSource = messageSource;
    //    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        log.warn("Returning HTTP 400 Bad Request", e);
    }

    @ExceptionHandler(TypeMismatchException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody Map<String, Object> handleTypeMismatch(TypeMismatchException e) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("error", "Type mismatch");
        map.put("cause", "Argument with the value " + e.getValue() + " is not valid");
        log.info("Handle TypeMismatch. Returning {}", map);
        return map;

    }

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody Map<String, Object> handleResourceNotFound(ResourceNotFoundException e) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("error", "Entity Not Found");
        map.put("cause", e.getMessage());
        log.info("Handle ResourceNotFound. Returning {}", map);
        return map;

    }

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e) throws Exception {
        log.error("An error was caught by the exception handler.", e);
        throw e;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ValidationErrorDTO processValidationError(MethodArgumentNotValidException e) {
        log.debug("Handling form validation error");

        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();

        return processFieldErrors(fieldErrors);
    }

    private ValidationErrorDTO processFieldErrors(List<FieldError> fieldErrors) {
        ValidationErrorDTO dto = new ValidationErrorDTO();

        for (FieldError fieldError : fieldErrors) {

            String localizedErrorMessage = null; //resolveLocalizedErrorMessage(fieldError);
            log.debug("Adding error message: {} to field: {}", localizedErrorMessage, fieldError.getField());
            dto.addFieldError(fieldError.getField(), fieldError.getCode(), localizedErrorMessage);
        }

        return dto;
    }

    //    private String resolveLocalizedErrorMessage(FieldError fieldError) {
    //        Locale currentLocale = LocaleContextHolder.getLocale();
    //        String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);
    //
    //        //If a message was not found, return the most accurate field error code instead.
    //        //You can remove this check if you prefer to get the default error message.
    //        if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
    //            String[] fieldErrorCodes = fieldError.getCodes();
    //            localizedErrorMessage = fieldErrorCodes[0];
    //        }
    //
    //        return localizedErrorMessage;
    //    }

}