AOPを使用した一括例外処理/結果の戻し

9153 ワード

日常業務における問題点
  • 異常
  • をキャプチャするために大量のtry/catchを使用する
  • は、制御層全体のコード可読性が極めて悪く、このような作業が繰り返され、複製が容易である.
  • 悪いコントローラコードは次のとおりです:
  • @RequestMapping("test/run/old")
    public JsonResponse testRunOld() {
        try {
            exampleService.runTest();
            System.out.println("    ");
            return JsonResponse.newOk();
        }catch (DataNotCompleteException e) {
            logger.error("something error occured!");
            return JsonResponse.newError(ErrorMsgEnum.DATA_NO_COMPLETE);
        } catch (Exception e) {
            return JsonResponse.newError();
        }
    
    }

    コードをこうします.
    @Controller
    public class TestController {
    
        @Autowired
        private IExampleService exampleService;
    
        @RequestMapping("test/run/aop")
        public JsonResponse testRunAop() throws Exception {
            exampleService.runTest();
            System.out.println("    ");
            return JsonResponse.newOk();
        }
    }
    @Service
    public class ExampleService implements IExampleService{
    
        @Override
        public void runTest() throws Exception {
    
            // do something
            System.out.println("run something");
            throw new CustomException(ErrorMsgEnum.DATA_NO_COMPLETE);
        }
    
    }
  • このようにしてから、コードにはtryとcatchが少なくなりました.これらのあちこちでコピーされているコードはもともと統一されるべきですが、aop以前はもっと良い処理方法がなく、コピーするしかありません.
  • 次に、serviceが異常を投げた後、controllerにcatchを追加する必要はありません.この操作は毎回5-15秒を浪費します(IDEのショートカットキーに慣れていない場合は、悪夢です).
  • 今あなたの異常は上に投げ出すだけで放っておけば(throws Exception)、ビジネスコード
  • に専念することができます.
    どのようにして完成しますか?実は原理はかなり簡単です.
    あれらの煩わしいtryをAOPの中で処理します
  • Spring AOPを使用して例外を統一的に処理し、バックエンドインタフェースの結果を統一的に返します.
  • は、カスタム例外とエラーフロントエンドプロンプトの列挙を使用して、メッセージ
  • をレイヤ毎に伝達する.
  • 新規例外情報クラスの代わりにエラー列挙を行い、ビジネス例外情報ファイルの数を
  • 減少させる.
    いくつかのコアクラスコード
  • ErrorMsgEnumエラー列挙
  • public enum ErrorMsgEnum {
    
        //       
        SUCCESS(true, 2000,"    ", "    "), 
    
        //     ,50  
        SYS_ERROR(false, 5000, "    ", " ,      ~"),
        PARAM_INVILAD(false, 5001, "      ", "      "), 
        DATA_NO_COMPLETE(false, 5002, "       ,   ", "       ,   ");
    
        private ErrorMsgEnum(boolean ok, int code, String msg ,String userMsg) {
            this.ok = ok;
            this.code = code;
            this.msg = msg;
            this.userMsg = userMsg;
        }
    
        private boolean ok;
        private int code;
        private String msg;
        private String userMsg;
    }
  • 制御層戻り結果POJO類
  • public class JsonResponse{
    
        String msg;
        Object data;
    
        public JsonResponse() {
            msg = "";
            data = null;
        }
    
        public static JsonResponse newOk() {
            JsonResponse response = new JsonResponse();
            response.setState(State.newOk());
            return response;
        }
    
        public static JsonResponse newOk(Object data) {
            JsonResponse response = new JsonResponse();
            response.setData(data);
            response.setState(State.newOk());
            return response;
        }
    
        public static JsonResponse newError() {
            JsonResponse response = new JsonResponse();
            response.setMsg("       !");
            return response;
        }
    
        public static JsonResponse newError(ErrorMsgEnum errorMsgEnum) {
            JsonResponse response = new JsonResponse();
            state.setMsg(errorMsgEnum.getErrorMsg());
            return response;
        }
    }
  • カスタム例外クラス
  • public class CustomException extends Exception {
    
        private ErrorMsgEnum errorMsgEnum;
    
        public CustomException(ErrorMsgEnum errorMsgEnum) {
            this.errorMsgEnum = errorMsgEnum;
        }
    }
  • AOPキャプチャ異常処理クラス
  • @Around("execution(public * com.jason.*.controller..*.*(..))")
    public JsonResponse serviceAOP(ProceedingJoinPoint pjp) throws Exception {
    
        JsonResponse newResultVo = null;
    
        try {
            return (JsonResponse) pjp.proceed();
        } catch (CustomException e) {
            logger.info("       :" + e.getMessage());
            ErrorMsgEnum errorMsgEnum = e.getErrorMsgEnum();
            if (Objects.nonNull(errorMsgEnum)) {
                newResultVo = JsonResponse.newError(errorMsgEnum);
            } else {
                newResultVo = JsonResponse.newError(e.getMessage());    
            }
        } catch (Exception e) {
            //          ,        ,    
            logger.error("       :", e);
            newResultVo = JsonResponse.newError();
        }
    
        return newResultVo;
    
    }

    Test && End
    これで、サービスまたはコントローラに直接例外を投げ出すことができ、コントローラメソッドごとに投げ出す例外をthrows Exceptionと定義すればよい.
    今回の処理を経て:
  • の最大のメリットはtry
  • がないことです.
  • 異常処理と戻り結果が統一され、あなたのチームメートが間違っていることを恐れません.

  • このプロジェクトは参考になります.githubに来て星をください.
    githubアドレス:https://github.com/JasonFirst/exceptionHandler