在业务处理逻辑中抛出自定义异常
public Object MethodSelf{
......
throw new SelfException(JSONObject.fromObject("{"key1":"value1"}", StringUtil.jsonConfig).toString());
}
public class SelfException extends RuntimeException {
/** serialVersionUID : */
private static final long serialVersionUID = -4172267101901373754L;
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SelfException(String message) {
super();
this.message = message;
}
}
spring.xml
<bean id="exceptionResolver" class="com.*.resolver.CustomExceptionResolver"></bean>
public class CustomExceptionResolver implements HandlerExceptionResolver {
private static Logger logger = LoggerFactory.getLogger(CustomExceptionResolver.class);
//wise自定义错误 throw 后需要截取exception.message中有效的json信息
private static final int SUBSTRLENG="com.*.SelfException : ".length();
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
ModelAndView modelAndView = new ModelAndView();
response.setStatus(HttpStatus.OK.value()); //设置状态码
response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
response.setCharacterEncoding("UTF-8"); //避免乱码
response.setHeader("Cache-Control", "no-cache, must-revalidate");
try {
if (exception instanceof SelfException) {
SelfException selfException= (SelfException) exception;
response.getWriter().write(selfException.getMessage());
logger.error("exceptions:" ,exception);
} else if (exception.getMessage().contains("SelfException:")) { //中台自定义错误异常
String exceptionMessages[] = exception.getMessage().split("\n");
if (exceptionMessages.length >= 2) {
if (exceptionMessages[0].length() >= SUBSTRLENG) {
String wiseExceptionMes = exceptionMessages[0].substring(SUBSTRLENG);
logger.info("WiseException={}", StringUtil.formatJson(JSONObject.fromObject(wiseExceptionMes).toString()));
response.getWriter().write(wiseExceptionMes);
}
}
logger.error("exceptions:", exception);
} else {
}
response.getWriter().write(JSONObject.fromObject("{"key1":"value1"}").toString());
}
} catch (Exception e) {
logger.error("全局异常处理失败", e);
}
return modelAndView;
}
}