SpringBoot全局异常处理

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;

/**
 * 业务异常
 * 
 * @author zhang.xlong
 *
 */
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;

	/**
	 * 404异常处理
	 */
	@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());
	}

	/**
	 * 405异常处理
	 */
	@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());
	}

	/**
	 * 415异常处理
	 */
	@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());
	}

	/**
	 * 500异常处理
	 */
	@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("业务异常======================================================");
		/*
		 * return commonHandler(request, response, exception.getClass().getSimpleName(),
		 * exception.getCode(), exception.getMessage());
		 */
		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<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		Map<String, String> 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(ResultJsonTools.build(ResponseCodeConstant.
				 * SYSTEM_ERROR, ResponseMessageConstant.APP_EXCEPTION,
				 * JSONObject.parseObject(JSON.toJSONString(entity))));
				 */
				response.getWriter().write(gson.toJson(entity));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值