org.shaf.server.controller.ExceptionHandlingController.java Source code

Java tutorial

Introduction

Here is the source code for org.shaf.server.controller.ExceptionHandlingController.java

Source

/**
 * Copyright 2014-2015 SHAF-WORK
 * 
 * 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 org.shaf.server.controller;

import javax.servlet.http.HttpServletRequest;

import org.shaf.core.util.Log;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * The controller for handling exceptions.
 * 
 * @author Mykola Galushka
 */
@ControllerAdvice
public class ExceptionHandlingController {

    /**
     * Defines a logger.
     */
    private static final Log LOG = Log.forClass(ExceptionHandlingController.class);

    /**
     * Handles the unexpected exception.
     * 
     * @param request
     *            the server request.
     * @param exception
     *            the occurred exception.
     * @return the view with exception dump and target IRL.
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception exception) {
        LOG.debug("CALL: error handler");

        exception.printStackTrace();

        return ViewError.getErrorView().header("url", request.getRequestURL().toString()).addException(exception)
                .warn("Check the system log for more details.");
    }

    @ExceptionHandler({ AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public ModelAndView handleAuthenticationException(HttpServletRequest request, Exception exception) {
        LOG.debug("CALL: error handler");

        exception.printStackTrace();

        return ViewError.getErrorView().header("url", request.getRequestURL().toString()).addException(exception)
                .warn("Check the system log for more details.");
    }
}