请求为返回的Interface添加不存在方法调用的错误处理方案
Great question! When working with dynamic interfaces where you can't be 100% sure if a method exists before calling it, there are a few practical ways to handle those "method not found" scenarios gracefully. Let's walk through them using your example code:
1. Explicit Method Check Before Calling
The simplest approach is to verify the method exists before invoking it. This is straightforward and works well for one-off calls:
let someInterface = await Controller.getApi('StatusData'); // Check if the method exists and is a function if (typeof someInterface.getMyInfo !== 'function') { // Throw a descriptive error, or handle it silently with a default response throw new Error(`Method 'getMyInfo' does not exist on the StatusData interface`); // Alternative: return a fallback response instead of throwing // return { success: false, error: "Requested method not available" }; } // Proceed only if the method exists let response = await someInterface.getMyInfo();
This gives you direct control over error handling at the point of call, but can get repetitive if you're calling multiple methods on the same interface.
2. Wrap the Interface with a Proxy (Automatic Interception)
For a more scalable solution, use a JavaScript Proxy to wrap the interface instance. This lets you intercept all property/method accesses and handle missing methods uniformly:
function createSafeApiProxy(apiInstance) { return new Proxy(apiInstance, { get(target, methodName) { // If the method doesn't exist or isn't a function, return a wrapper that throws if (typeof target[methodName] !== 'function') { return async () => { throw new TypeError(`Method '${methodName}' is not defined on this API interface`); }; } // Return the original method if it exists return target[methodName]; } }); } // Usage with your code let someInterface = await Controller.getApi('StatusData'); let safeInterface = createSafeApiProxy(someInterface); try { let response = await safeInterface.getMyInfo(); // Throws if method doesn't exist } catch (err) { console.error("Method call failed:", err.message); // Add your custom handling here: log to monitoring, show user feedback, etc. }
With this approach, you only need to wrap the interface once, and all subsequent method calls will automatically trigger the error handling logic. Perfect for when you're working with multiple methods on the same dynamic interface.
3. Custom Error Classes for Granular Handling
To make error handling more precise (e.g., distinguishing "method not found" errors from network errors), create a custom error class:
class InterfaceMethodNotFoundError extends Error { constructor(methodName, interfaceName) { super(`Method '${methodName}' not found on ${interfaceName} interface`); this.name = 'InterfaceMethodNotFoundError'; this.methodName = methodName; this.interfaceName = interfaceName; } } // Use this in your check or Proxy: if (typeof someInterface.getMyInfo !== 'function') { throw new InterfaceMethodNotFoundError('getMyInfo', 'StatusData'); } // Then catch it specifically: try { let response = await someInterface.getMyInfo(); } catch (err) { if (err instanceof InterfaceMethodNotFoundError) { console.error(`Missing method on ${err.interfaceName}: ${err.methodName}`); // Handle this specific error type (e.g., show user a feature unavailable message) } else { // Handle other errors like network failures console.error("Unexpected error:", err); } }
This makes it easy to separate different error types and apply targeted handling logic.
Which Approach to Choose?
- Use explicit checks for simple, one-off method calls.
- Use a Proxy wrapper if you're working with multiple methods on the same dynamic interface.
- Add custom errors if you need to distinguish between error types for more granular handling.
内容的提问来源于stack exchange,提问作者Ted

