I’m having trouble with a custom error class in TypeScript where the modified error message does not display correctly, I just get the error message returned from the API call.
My customError classs–
export class CustomError extends Error {
cod:string;
constructor(cod:string , message: string){
super(message);
this.cod = cod;
Object.setPrototypeOf(this , new.target.prototype);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
The class inheriting–
import { CustomError } from "./CustomError";
export class CityNotFoundError extends CustomError {
constructor(cod:string , message: string){
const errMsg:string = message + " :The city you provided was not found,Please verify"
super(cod,errMsg);
}
}
The error handler function.
import { CityNotFoundError } from "../Errors/CityNotFoundError";
export function ErrorHandler(cod: string , message: string){
switch(cod){
case '404':
const errMsg:string = message + " :The city you provided was not found,Please verify"
return new CityNotFoundError(cod,errMsg);
}
}
This is the function
app.get('/',async (req:Request,res:Response) =>{
await fetch(`https://api.openweathermap.org/data/2.5/weather?q={location}&&appid={API_KEY}`).
then(async(response) =>{
const data = await response.json();
console.log(data)
res.json(data);
}).
catch(async(err) =>{
const error = ErrorHandler(err.cod , err.message)!;
console.error(error.stack);
res.status(500).json({
code: error.cod,
message: error.message,
});
})
})
I get this error { cod: ‘404’, message: ‘city not found’ }
but I want this..
{ cod: ‘404’, message: ‘city not found: :The city you provided was not found,Please verify’ }
What might be causing the issue where the error message is not modified as expected? How can I ensure that the additional context I add in the CityNotFoundError constructor is included in the error message when it is logged?
3
I found the issue,I just had to check the response json for an unsuccessful response and then throw the error.
fetch(`https://api.openweathermap.org/data/2.5/weather?q={Location}&&appid={API_KEY}`).
then(async(response) =>{
if(!response.ok){
const errData = await response.json();
console.log(errData)
throw ErrorHandler(errData.cod,errData.message);
}
const data = await response.json();
res.json(output);