2017-07-28 13 views
0

私はDartでクライアントサーバーアプリケーションを開発中で、tutorialに従っています。私のサーバーコードはおおよそそれに基づいています。私のサーバーのAPIコードでDartのサーバーAPIコードから例外をスローする方法はありますか?

、何かがうまくいかないとき、私は例えば、例外をスローします:

void checkEverything() { 
    if(somethingWrong) 
    throw new RpcError(400, "Something Wrong", "Something went wrong!"); 
} 

@ApiMethod(path: 'myservice/{arg}') 
Future<String> myservice(String arg) async { 
    checkEverything(); 
    // ... 
    return myServiceResponse; 
} 

とその例外は、例えば、メインサーバで処理されなければなりません

// ... 
var apiResponse; 
try { 
    var apiRequest = new HttpApiRequest.fromHttpRequest(request); 
    apiResponse = await _apiServer.handleHttpApiRequest(apiRequest); 
} catch (error, stack) { 
    var exception = error is Error ? new Exception(error.toString()) : error; 
    if((error is RpcError && error.statusCode==400) { 
    // My code for creating the HTTP response 
    apiResponse = new HttpApiResponse.error(
     HttpStatus.BAD_REQUEST, "Something went wrong", exception, stack); 
    } 
    else { 
    // standard error processing from the Dart tutorial 
    apiResponse = new HttpApiResponse.error(
     HttpStatus.INTERNAL_SERVER_ERROR, exception.toString(), 
     exception, stack); 
    } 
} 

(スニペット、完全なコードのsans私のエラー処理のためtutorialを参照してください)。

ただし、私の例外は上記のcatch節には決して達しません。代わりに、ターンで、INTERNAL_SERVER_ERROR(500)スローされ、_apiServer.handleHttpApiRequest(apiRequest);に巻き込まれるようだ:

[WARNING] rpc: Method myservice returned null instead of valid return value 
[WARNING] rpc: 
Response 
    Status Code: 500 
    Headers: 
    access-control-allow-credentials: true 
    access-control-allow-origin: * 
    cache-control: no-cache, no-store, must-revalidate 
    content-type: application/json; charset=utf-8 
    expires: 0 
    pragma: no-cache 
    Exception: 
    RPC Error with status: 500 and message: Method with non-void return type returned 'null' 

Unhandled exception: 
RPC Error with status: 400 and message: Something went wrong! 
#0  MyApi.myservice (package:mypackage/server/myapi.dart:204:24) 
[...] 

これは、クライアントのための非常に具体的ではありません。私は間違いが起こったと伝えたい、良い見返りを返さないようにしたい。では、Dartのサーバーサイド例外を処理し、その情報をクライアントに渡す適切な方法は何ですか?

答えて

1

OK、私は問題を解決したと思います。 throw句は、明らかにAPIメソッド自体でなければならず、従属メソッドではありません。すなわち:

@ApiMethod(path: 'myservice/{arg}') 
Future<String> myservice(String arg) async { 
    if(somethingWrong) 
    throw new RpcError(400, "Something Wrong", "Something went wrong!"); 
    // ... 
    return myServiceResponse; 
} 

ない:

void checkEverything() { 
    if(somethingWrong) 
    throw new RpcError(400, "Something Wrong", "Something went wrong!"); 
} 

@ApiMethod(path: 'myservice/{arg}') 
Future<String> myservice(String arg) async { 
    checkEverything(); 
    // ... 
    return myServiceResponse; 
} 
関連する問題