<>需要的几个基本类:
ResultCode
Response
ResponseResult
CommonCode: 自定义code信息
/** * Created by 李新宇 * 2019-07-31 17:54 * <p> * 10000-- 通用错误代码 * 22000--
媒资错误代码 * 23000-- 用户中心错误代码 * 24000-- cms错误代码 * 25000-- 文件系统 */ public interface
ResultCode { //操作是否成功,true为成功,false操作失败 boolean success(); //操作代码 int code();
//提示信息 String message(); } /** * Created by 李新宇 * 2019-07-31 17:54 */ public
interface Response { public static final boolean SUCCESS = true; public static
final int SUCCESS_CODE = 10000; } /** * Created by 李新宇 * 2019-07-31 17:54 */
@Data @ToString @NoArgsConstructor public class ResponseResult implements
Response { //操作是否成功 boolean success = SUCCESS; //操作代码 int code = SUCCESS_CODE;
//提示信息 String message; public ResponseResult(ResultCode resultCode) { this.
success= resultCode.success(); this.code = resultCode.code(); this.message =
resultCode.message(); } public static ResponseResult SUCCESS() { return new
ResponseResult(CommonCode.SUCCESS); } public static ResponseResult FAIL() {
return new ResponseResult(CommonCode.FAIL); } } /** * 自定义code信息 * Created by
李新宇 * 2019-07-31 17:54 */ @ToString public enum CommonCode implements ResultCode
{ SUCCESS(true,10000,"操作成功!"), FAIL(false,11111,"操作失败!"), UNAUTHENTICATED(false,
10001,"此操作需要登陆系统!"), UNAUTHORISE(false,10002,"权限不足,无权操作!"), SERVER_ERROR(false,
99999,"抱歉,系统繁忙,请稍后重试!"); // private static ImmutableMap<Integer, CommonCode>
codes ; //操作是否成功 boolean success; //操作代码 int code; //提示信息 String message;
private CommonCode(boolean success,int code, String message){ this.success =
success; this.code = code; this.message = message; } @Override public boolean
success() { return success; } @Override public int code() { return code; }
@Override public String message() { return message; } }
自定义异常开始
ExceptionCast: 抛出自定义异常
ExceptionCatch: 统一异常捕获类
/** * 抛出自定义异常 * <p> * Created by 李新宇 * 2019-07-31 17:54 */ public class
ExceptionCast { //使用此静态方法抛出自定义异常 public static void cast(ResultCode resultCode)
{ throw new CustomException(resultCode); } } /** * 统一异常捕获类 * <p> * Created by
李新宇 * 2019-07-31 17:58 */ @ControllerAdvice //控制器增强 public class ExceptionCatch
{ private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.
class); //捕获CustomException此类异常 @ExceptionHandler(CustomException.class)
@ResponseBody public ResponseResult customException(CustomException
customException) { //记录日志 LOGGER.error("catch exception: {}", customException.
getMessage()); ResultCode resultCode = customException.getResultCode(); return
new ResponseResult(resultCode); } }
<>使用
if (cmsPage1 != null) { ExceptionCast.cast(CommonCode.FAIL); }
技术
今日推荐