Skip to content

Controller 异常响应处理

shell
package cloud.xuxiaowei.validation.config;

import lombok.extern.slf4j.Slf4j;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * {@link Controller}、{@link RestController} 异常处理
 * <p>
 * 1. {@link ControllerAdvice} 不支持通配符
 * <p>
 * 2. 直接扫描 {@link Controller}、{@link RestController} 父包
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
@ControllerAdvice({ "cloud.xuxiaowei" })
public class ControllerAdviceConfig {

	/**
	 * 异常 处理
	 * <p>
	 * 1. 此处以响应 JSON 数据为例
	 * <p>
	 * 2. 此处为拦截所有异常,请在使用时分别拦截指定异常,方便分类处理
	 * @param exception 异常
	 * @param request 请求
	 * @param response 响应
	 * @return 返回 异常数据
	 */
	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Map<String, Object> exception(Exception exception, HttpServletRequest request,
			HttpServletResponse response) {

		log.error("拦截到 Controller 异常:", exception);

		Map<String, Object> result = new HashMap<>();

		result.put("code", 500);
		result.put("msg", exception.getMessage());

		return result;
	}

}
shell
package cloud.xuxiaowei.validation.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * {@link Controller}、{@link RestController} 异常处理
 * <p>
 * 1. {@link ControllerAdvice} 不支持通配符
 * <p>
 * 2. 直接扫描 {@link Controller}、{@link RestController} 父包
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
@ControllerAdvice({ "cloud.xuxiaowei" })
public class ControllerAdviceConfig {

	/**
	 * 异常 处理
	 * <p>
	 * 1. 此处以响应 JSON 数据为例
	 * <p>
	 * 2. 此处为拦截所有异常,请在使用时分别拦截指定异常,方便分类处理
	 * @param exception 异常
	 * @param request 请求
	 * @param response 响应
	 * @return 返回 异常数据
	 */
	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Map<String, Object> exception(Exception exception, HttpServletRequest request,
			HttpServletResponse response) {

		log.error("拦截到 Controller 异常:", exception);

		Map<String, Object> result = new HashMap<>();

		result.put("code", 500);
		result.put("msg", exception.getMessage());

		return result;
	}

}