安卓前端提出对接口出现的异常,做统一的错误页面。刚好csdn 小D课堂有统一异常处理方式。实现很简单:
/**
*
* @描述: 捕获全局异常,方便前端做错误提示页面
*/
@RestControllerAdvice
public class CustomExtHandler
{
private static final Logger logger = LoggerFactory.getLogger(CustomExtHandler.class);
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
Object handleException(Exception e,HttpServletRequest request){
logger.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
return new Result<Object>(ErrorCode.inner_error, e.getMessage());
}
}
或者
@ExceptionHandler(value=Exception.class)
//@ResponseBody
Object handleException(Exception e,HttpServletRequest request){
LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
也可以自定义异常:
public class MyException extends RuntimeException {
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}