2017-07-28 60 views
0

我正在开发Dart中的客户端 - 服务器应用程序,并且一直遵循tutorial。我的服务器代码大致基于它。如何从Dart的服务器API代码中抛出异常?

在我的服务器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); 
    } 
} 

(片段中,看到tutorial完整的代码SANS我的错误处理)。

但是,我的例外从来没有达到上述catch条款。相反,它似乎被卷进_apiServer.handleHttpApiRequest(apiRequest);,其中,在转弯,抛出INTERNAL_SERVER_ERROR(500):

[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

好的,我想我解决了这个问题。条款显然必须在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; 
}