All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ajaxjs.spring.GlobalExceptionHandler Maven / Gradle / Ivy

Go to download

AJAXJS aims to full-stack, not only the server-side framework, but also integrates the front-end library. It'€™s written in HTML5 + Java, a successor to the JVM platform, efficient, secure, stable, cross-platform and many other advantages, but it abandoned the traditional enterprise architecture brought about by the large and bloated, emphasizing the lightweight, and fast, very suitable for the Internet fast application.

The newest version!
package com.ajaxjs.spring;

import com.ajaxjs.framework.BaseController;
import com.ajaxjs.util.logger.LogHelper;
import com.ajaxjs.util.map.JsonHelper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常拦截器
 * 
 * @author Frank Cheung
 *
 */
public class GlobalExceptionHandler implements HandlerExceptionResolver {
	private static final LogHelper LOGGER = LogHelper.getLog(GlobalExceptionHandler.class);

	/**
	 * 判断是否期望 JSON 的结果
	 * 
	 * @return true 表示为希望是 JSON
	 */
	public static boolean isJson(HttpServletRequest request) {
		String accept = request.getHeader("Accept");
		return accept != null && "application/json".equals(accept);
	}

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		LOGGER.warning(ex);

		if (isJson(request)) {
			String msg = ex.getMessage();

			if (msg == null)
				msg = ex.toString();

			msg = JsonHelper.javaValue2jsonValue(JsonHelper.jsonString_covernt(msg));

			/* 使用response返回 */
			response.setStatus(HttpStatus.OK.value()); // 设置状态码
			response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
			response.setCharacterEncoding("UTF-8"); // 避免乱码
			response.setHeader("Cache-Control", "no-cache, must-revalidate");

			try {
				response.getWriter().write(BaseController.jsonNoOk(msg));
			} catch (IOException e) {
				LOGGER.warning(e);
			}

			return new ModelAndView();
		} else
			return null;// 默认视图,跳转 jsp
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy