全局异常处理 GlobalExceptionHandler
@ControllerAdvice(basePackages = "com.xxx.testssm")
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonResult<Object> jsonErrorHandler(HttpServletRequest req, Exception ex) throws Exception {
JsonResult<Object> value = null;
if (ex != null) {
if (ex instanceof ServiceException) {
log.error("Occur service exception: {}", ex.getMessage());
value = new JsonResult<Object>(((ServiceException) ex).getCode(), ex.getMessage());
}
else {
log.error("op=global_exception_handler_print_error", ex);
value = new JsonResult<Object>(-1, ex.getMessage() == null ? ex.toString() : ex.getMessage());
}
}
return value;
}
}
自定义异常 ServiceException
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 9213584003139969215L;
private int code;
public ServiceException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}