Production error handling for Express APIs — error middleware, async wrappers,
89
86%
Does it follow best practices?
Impact
97%
2.02xAverage score across 4 eval scenarios
Passed
No known issues
Build an Express TypeScript API that fetches weather data from an external service and returns it to clients.
Endpoints:
GET /api/weather/:city -- returns current weather for the specified cityUse this simulated external service client (create it as src/weather-client.ts):
// src/weather-client.ts
export interface WeatherData {
city: string;
temperature: number;
conditions: string;
humidity: number;
}
export async function fetchWeather(city: string): Promise<WeatherData> {
await new Promise(r => setTimeout(r, 100));
if (city === 'timeout-city') throw new Error('ETIMEDOUT');
if (city === 'down-city') {
const err: any = new Error('Service temporarily unavailable');
err.status = 503;
throw err;
}
if (city === 'unknown-city') throw new Error('City not found in weather database');
return {
city,
temperature: Math.round(15 + Math.random() * 20),
conditions: ['sunny', 'cloudy', 'rainy', 'partly cloudy'][Math.floor(Math.random() * 4)],
humidity: Math.round(30 + Math.random() * 50),
};
}The API will be consumed by a mobile app, so responses should always be JSON.
Produce:
src/weather-client.ts -- the external service client (copy from above)src/server.ts -- server entry pointsrc/app.ts -- Express application setupsrc/routes/weather.ts -- route handlerpackage.json -- with dependenciesYou may create additional files as needed.