Java项目对系统抛出的异常做分类提示,或后续处理。
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
//方法一:未细化异常,全部抓取
@ExceptionHandler(Exception.class)
public JSONObject handleException(Exception e, HttpServletRequest httpServletRequest) {
//方法内部的样例和返回值类型可以根据需要自行定义
log.error("系统异常{0}", e);
JSONObject res = new JSONObject();
String messageId = httpServletRequest.getHeader(Constant.MESSAGE_ID);
res.put(Constant.STATUS, Constant.E);
res.put(Constant.CODE, String.valueOf(ReturnT.FAIL_CODE));
res.put(Constant.MESSAGE, "系统异常");
res.put(Constant.MESSAGEID, messageId);
res.put(Constant.REQUEUE, String.valueOf(false));
return res;
}
//方法二:运行时异常
@ExceptionHandler(RuntimeException.class)
public JSONObject runtimeException(RuntimeException e, HttpServletRequest httpServletRequest) {
//方法内部的样例和返回值类型可以根据需要自行定义
return new JSONObject();
}
//方法三:自定义异常
@ExceptionHandler({BaseException.class})
public JSONObject baseException(BaseException e, HttpServletRequest httpServletRequest) {
return new JSONObject();
}
}
自定义异常类:
public class BaseException extends RuntimeException {
}

8396

被折叠的 条评论
为什么被折叠?



