spring boot----全局异常处理

全局异常处理:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 异常处理类
 */
@ControllerAdvice
public class GlobalExceptionController {
	private static Logger logger = LoggerFactory.getLogger(GlobalExceptionController.class);

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = MissingServletRequestParameterException.class)
	@ResponseBody
	public Map<String, Object> handleMissingServletRequestParameterException(
			MissingServletRequestParameterException e) {
		logger.error("缺少请求参数", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "缺少请求参数");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = HttpMessageNotReadableException.class)
	@ResponseBody
	public Map<String, Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		logger.error("参数解析失败", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数解析失败");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		logger.error("参数验证失败", e);
		BindingResult result = e.getBindingResult();
		FieldError error = result.getFieldError();
		String field = error.getField();
		String code = error.getDefaultMessage();
		String message = String.format("%s:%s", field, code);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数验证失败");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = IllegalArgumentException.class)
	@ResponseBody
	public Map<String, Object> handleIllegalArgumentException(IllegalArgumentException e) {
		logger.error("IllegalArgumentException", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数错误");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public Map<String, Object> handleBindException(BindException e) {
		logger.error("参数绑定失败", e);
		BindingResult result = e.getBindingResult();
		FieldError error = result.getFieldError();
		String field = error.getField();
		String code = error.getDefaultMessage();
		String message = String.format("%s:%s", field, code);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数绑定失败");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = ConstraintViolationException.class)
	@ResponseBody
	public Map<String, Object> handleServiceException(ConstraintViolationException e) {
		logger.error("参数验证失败", e);
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		ConstraintViolation<?> violation = violations.iterator().next();
		String message = violation.getMessage();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数验证失败");
		return map;
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = ValidationException.class)
	@ResponseBody
	public Map<String, Object> handleValidationException(ValidationException e) {
		logger.error("参数验证失败", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "400");
		map.put("message", "参数验证失败");
		return map;
	}

	/**
	 * 404 - Not Found
	 */
	@ResponseStatus(HttpStatus.NOT_FOUND)
	@ExceptionHandler(value = NoHandlerFoundException.class)
	@ResponseBody
	public Map<String, Object> noHandlerFoundException(NoHandlerFoundException e) {
		logger.error("Not Found", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "404");
		map.put("message", "Not Found");
		return map;
	}

	/**
	 * 405 - Method Not Allowed
	 */
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
	@ResponseBody
	public Map<String, Object> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		logger.error("不支持当前请求方法", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "405");
		map.put("message", "不支持当前请求方法");
		return map;
	}

	/**
	 * 415 - Unsupported Media Type
	 */
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
	@ResponseBody
	public Map<String, Object> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
		logger.error("不支持当前媒体类型", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "415");
		map.put("message", "不支持当前媒体类型");
		return map;
	}

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
	@ResponseBody
	public Map<String, Object> SQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
		logger.error("sql异常", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "500");
		map.put("message", "SQL异常");
		return map;
	}



	/**
	 * 500 - Internal Server Error
	 */

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
	public Map<String, Object> handleException(Exception e) {
		logger.error("通用异常", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "500");
		map.put("message", "Exception");
		return map;
	}


	/**
	 * 获取其它异常。包括500
	 *
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	//@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Map<String, Object> defaultErrorHandler(Exception e) {
		logger.error("Exception", e);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "500");
		map.put("message", "服务器错误,请联系管理员");
		return map;
	}

}```

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值