栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java全局异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java全局异常处理

entity

package co.sekisuihouse.apServer.pojo.exception;

import java.io.Serializable;
import java.util.Date;


public class ExceptionEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	private String message;

	private int code;

	private String error;

	private String path;

	private Date timestamp = new Date();

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}
}
自定义异常
package co.sekisuihouse.apServer.exception;

import org.springframework.stereotype.Repository;


public class BaseException extends RuntimeException {

	
	private static final long serialVersionUID = 1L;

	private Integer code = 0;

	public BaseException(Integer code, String message) {
		super(message);
		this.code = code;
	}

	public Integer getCode() {
		return code;
	}

}
业务异常
package co.sekisuihouse.apServer.exception;


public class BusinessException extends BaseException {

	
	private static final long serialVersionUID = 1L;

	public BusinessException(Integer code, String message) {
		super(code, message);
	}
	
}

配置
package co.sekisuihouse.apServer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Configuration
public class JsonConfig {

	@Bean
	public Gson getGson() {
		return new GsonBuilder().disableHtmlEscaping().create();
	}

}
异常处理
package co.sekisuihouse.apServer.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
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 org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import co.sekisuihouse.apServer.exception.BaseException;
import co.sekisuihouse.apServer.pojo.exception.ExceptionEntity;


@ControllerAdvice
public class GlobalExceptionHandler {

	@Autowired
	private Gson gson;

	
	@ExceptionHandler(value = NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public ModelAndView errorHandler(HttpServletRequest request, NoHandlerFoundException exception,
			HttpServletResponse response) {
		return commonHandler(request, response, exception.getClass().getSimpleName(), HttpStatus.NOT_FOUND.value(),
				exception.getMessage());
	}

	
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ModelAndView errorHandler(HttpServletRequest request, HttpRequestMethodNotSupportedException exception,
			HttpServletResponse response) {
		return commonHandler(request, response, exception.getClass().getSimpleName(),
				HttpStatus.METHOD_NOT_ALLOWED.value(), exception.getMessage());
	}

	
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public ModelAndView errorHandler(HttpServletRequest request, HttpMediaTypeNotSupportedException exception,
			HttpServletResponse response) {
		return commonHandler(request, response, exception.getClass().getSimpleName(),
				HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), exception.getMessage());
	}

	
	@ExceptionHandler(value = Exception.class)
	public ModelAndView errorHandler(HttpServletRequest request, Exception exception, HttpServletResponse response) {
		return commonHandler(request, response, exception.getClass().getSimpleName(),
				HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage());
	}

	
	@ResponseBody
	@ExceptionHandler(value = BaseException.class)
	//@ResponseStatus(HttpStatus.NOT_FOUND)
	private String errorHandler(HttpServletRequest request, BaseException exception, HttpServletResponse response) {
		System.out.println("业务异常======================================================");
		
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("code", exception.getCode().toString());
		jsonObject.addProperty("message", exception.getMessage());
		jsonObject.addProperty("getLocalizedMessage", exception.getLocalizedMessage());
		jsonObject.addProperty("HttpStatus", exception.getCause().toString());
		
		return gson.toJson(jsonObject);
	}

	
	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public ExceptionEntity validExceptionHandler(BindException exception, HttpServletRequest request,
			HttpServletResponse response) {
		List fieldErrors = exception.getBindingResult().getFieldErrors();
		Map errors = new HashMap<>();
		for (FieldError error : fieldErrors) {
			errors.put(error.getField(), error.getDefaultMessage());
		}
		ExceptionEntity entity = new ExceptionEntity();
		// entity.setMessage(JSON.toJSONString(errors));

		entity.setMessage(gson.toJson(errors));
		entity.setMessage(errors.toString());
		entity.setPath(request.getRequestURI());
		entity.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
		entity.setError(exception.getClass().getSimpleName());
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		return entity;
	}

	
	private ModelAndView commonHandler(HttpServletRequest request, HttpServletResponse response, String error,
			int httpCode, String message) {
		ExceptionEntity entity = new ExceptionEntity();
		entity.setPath(request.getRequestURI());
		entity.setError(error);
		entity.setCode(httpCode);
		entity.setMessage(message);
		return determineOutput(request, response, entity);
	}

	
	private ModelAndView determineOutput(HttpServletRequest request, HttpServletResponse response,
			ExceptionEntity entity) {
		if (!(request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null
				&& request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
			ModelAndView modelAndView = new ModelAndView("error");
			modelAndView.addObject("exception", entity);
			return modelAndView;
		} else {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setCharacterEncoding("UTF8");
			response.setHeader("Content-Type", "application/json");
			try {
				
				response.getWriter().write(gson.toJson(entity));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1013432.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号