[符号化モード]記録異常

1716 ワード

背景
デバッグしたマシンで例外が発生しない場合は、例外を記録してリモートサーバに送信する必要があります.
シーン
ユーザーのいくつかの操作、または特定の携帯電話で異常が発生した場合、開発者に異常を送信する必要があるモバイルアプリケーションを作成します.
≪インスタンス|Instance|emdw≫
Reporter.java
public interface Reporter {
    public void report(Throwable t);
}

ExceptionReporter.java
public class ExceptionReporter {
    public static final Reporter PrintException = new Reporter() {
        @Override
        public void report(Throwable t) {
            System.out.println(t.toString());
        }
    };

    private static Reporter defalutReporter = PrintException;

    public static Reporter getPrintException(){
        return PrintException;
    }

    public static Reporter getExceptionReporter(){
        return defalutReporter;
    }

    public static Reporter setExceptionReporter(Reporter reporter){
        defalutReporter = reporter;
        return defalutReporter;
    }
}

EmailExceptionReporter.java
public class EmailExceptionReporter implements Reporter {
    @Override
    public void report(Throwable t) {
        sendMessage(t.toString());
    }

    private void sendMessage(String message){
        // Send email
    }
}

Test.java
public class Test {
    public static void main(String args[]){
        try{
            int a[] = {0, 0};
            System.out.print(a[2]);
        }catch (Exception e){
            ExceptionReporter.getPrintException().report(e);
        }

        try{
            String b = null;
            b.toCharArray();
        }catch (Exception e){
            ExceptionReporter.setExceptionReporter(new EmailExceptionReporter()).report(e);
        }
    }
}