1.实现思路
1.1 创建 GlobleExceptionHandler ,用注解@ControllerAdvice,@ResponseBody 修饰,
@ExceptionHandler(value=Exception.class) 定义处理哪种异常,传入参数HttpServletRequest request ,Exception e ,判断传入的异常类型instacneof GlobalException ,如果是绑定异常BindExcpetion获取getAllErrors 返回CodeMsg.BIND_ERROR,如果是其他异常返回服务端异常。
package com.zengjx.miaosha.exception;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.zengjx.miaosha.result.CodeMsg;
import com.zengjx.miaosha.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class)
public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
e.printStackTrace();
if(e instanceof GlobalException) {
GlobalException ex = (GlobalException)e;
return Result.error(ex.getCm());
}else if(e instanceof BindException) {
BindException ex = (BindException)e;
List<ObjectError> errors = ex.getAllErrors();
ObjectError error = errors.get(0);
String msg = error.getDefaultMessage();
return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
}else {
return Result.error(CodeMsg.SERVER_ERROR);
}
}
}
1.2. 定义全局异常类GlobalException 继承与RuntimeException
package com.zengjx.miaosha.exception;
import com.zengjx.miaosha.result.CodeMsg;
public class GlobalException extends RuntimeException{
private static final long serialVersionUID = 1L;
private CodeMsg cm;
public GlobalException(CodeMsg cm) {
super(cm.toString());
this.cm = cm;
}
public CodeMsg getCm() {
return cm;
}
}
Rsingstarzengjx 发布了215 篇原创文章 · 获赞 8 · 访问量 4万+ 私信 关注