Java tutorial
/* * Copyright 2016-2017 the original author or authors. * * 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 com.wiiyaya.consumer.web.main.controller; import com.wiiyaya.consumer.web.main.constant.MainURIResource; import com.wiiyaya.framework.common.exception.BusinessException; import com.wiiyaya.framework.common.exception.MaxSessionException; import com.wiiyaya.framework.common.exception.PageNotFoundException; import com.wiiyaya.framework.common.exception.SessionTimeoutException; import com.wiiyaya.framework.common.exception.ValidateException; import com.wiiyaya.framework.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.security.access.AccessDeniedException; import org.springframework.stereotype.Controller; 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.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import org.springframework.web.util.WebUtils; import javax.servlet.http.HttpServletRequest; import java.util.LinkedHashMap; import java.util.Map; /** * * <p></p> * * <p>??</p> * * <p></p> * * @author wiiyaya * */ @ControllerAdvice @Controller public class ExceptionController { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class); private static final String MSG_ERROR_SESSION_MAXIMUM = "error.session.maximum"; private static final String MSG_ERROR_SESSION_TIMEOUT = "error.session.timeout"; private static final String MSG_ERROR_NO_PRIVILEGE = "error.noPrivilege"; private static final String MSG_ERROR_VALIDATE = "error.validate"; private static final String MSG_ERROR_PAGE_NOT_FOUND = "error.pageNotFound"; private static final MappingJackson2JsonView DEFAULT_JSON_VIEW = new MappingJackson2JsonView(); @Autowired private MessageSource messageSource; @RequestMapping(MainURIResource.PATH_ERROR_MAX_SESSIONS) public String maxSessions() throws MaxSessionException { throw new MaxSessionException(); } @RequestMapping(MainURIResource.PATH_ERROR_TIME_OUT) public String timeout() throws SessionTimeoutException { throw new SessionTimeoutException(); } @RequestMapping(MainURIResource.PATH_ERROR_ALL) public String error(HttpServletRequest request) throws Throwable { Integer code = (Integer) request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE); Throwable exception = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE); String simpleMsg = (String) request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE); if (exception != null) { throw getRootCause(exception); } else { switch (code) { case 404: throw new PageNotFoundException(); case 403: throw new AccessDeniedException(simpleMsg); default: throw new Exception(simpleMsg); } } } /** * ?? * @param request ? * @return ExceptionDto JSON */ @ExceptionHandler(value = MaxSessionException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView maxSessionException(HttpServletRequest request) { String errorMessage = messageSource.getMessage(MSG_ERROR_SESSION_MAXIMUM, null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.UNAUTHORIZED, MSG_ERROR_SESSION_MAXIMUM, errorMessage); } /** * ? * @param request ? * @return ExceptionDto JSON */ @ExceptionHandler(value = SessionTimeoutException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView sessionTimeoutException(HttpServletRequest request) { String errorMessage = messageSource.getMessage(MSG_ERROR_SESSION_TIMEOUT, null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.UNAUTHORIZED, MSG_ERROR_SESSION_TIMEOUT, errorMessage); } /** * ?? * @param request ? * @return ExceptionDto JSON */ @ExceptionHandler(value = AccessDeniedException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView accessDeniedException(HttpServletRequest request) { String errorMessage = messageSource.getMessage(MSG_ERROR_NO_PRIVILEGE, null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.UNAUTHORIZED, MSG_ERROR_NO_PRIVILEGE, errorMessage); } /** * * @param request ? * @param exception * @return ExceptionDto JSON */ @ExceptionHandler(value = ValidateException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public ModelAndView businessException(HttpServletRequest request, ValidateException exception) { String filedName = messageSource.getMessage(exception.getCode(), null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.FORBIDDEN, MSG_ERROR_VALIDATE, filedName + exception.getDefaultMessage()); } /** * * @param request ? * @param exception * @return ExceptionDto JSON */ @ExceptionHandler(value = BusinessException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public ModelAndView businessException(HttpServletRequest request, BusinessException exception) { String errorMessage = messageSource.getMessage(exception.getCode(), exception.getArguments(), LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.FORBIDDEN, exception.getCode(), errorMessage); } /** * ?? * @param request ? * @return ExceptionDto JSON */ @ExceptionHandler(value = PageNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ModelAndView pageNotFoundException(HttpServletRequest request) { String errorMessage = messageSource.getMessage(MSG_ERROR_PAGE_NOT_FOUND, null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.NOT_FOUND, MSG_ERROR_PAGE_NOT_FOUND, errorMessage); } /** * * @param request ? * @param exception * @return ExceptionDto JSON */ @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView springErrorHand(HttpServletRequest request, Exception exception) { String simpleMsg = (String) request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE); String errorCode = exception == null ? simpleMsg : exception.getClass().getSimpleName(); String errorMessage = exception == null ? simpleMsg : exception.getMessage(); LOGGER.error("Error catch: statusCode[{}], errorMessage[{}], errorUrl[{}]", HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMessage, request.getRequestURI(), exception); return prepareExceptionInfo(request, HttpStatus.INTERNAL_SERVER_ERROR, errorCode, errorMessage); } private ModelAndView prepareExceptionInfo(HttpServletRequest request, HttpStatus httpStatus, String errorCode, String errorMessage) { Map<String, Object> models = new LinkedHashMap<>(); models.put("statusCode", httpStatus.value()); models.put("errorCode", errorCode); models.put("errorMessage", errorMessage); ModelAndView modelAndView = new ModelAndView(); if (noNeedWrapper(request)) { modelAndView.setView(DEFAULT_JSON_VIEW); modelAndView.addAllObjects(models); return modelAndView; } else { modelAndView.setViewName("error"); modelAndView.addAllObjects(models); return modelAndView; } } private boolean noNeedWrapper(HttpServletRequest request) { String xmlHttpRequest = request.getHeader("X-Requested-With"); String noWrapperParameter = StringUtils.defaultString(request.getParameter("noSiteMeshWapper")); return "XMLHttpRequest".equalsIgnoreCase(xmlHttpRequest) || noWrapperParameter.equalsIgnoreCase("true") || noWrapperParameter.equalsIgnoreCase("yes") || noWrapperParameter.equals("1"); } private Throwable getRootCause(Throwable exception) { if (exception.getCause() != null) { return getRootCause(exception.getCause()); } return exception; } }