What will be the type of error
in action.ts that is handled by handled in catch block of worker saga ?
action.ts
const actionError = (error): IFluxStandardAction => {
return {
type: ACTIONTYPE_ERROR,
payload: error
};
};
saga.ts
function* WorkerSaga(value) {
try {
const { payload } = value;
const response: Response = yield call(clientApi, payload);
yield put(Actions.Success(response));
} catch (error) {
yield put(Actions.Error(error));
}
}
Parameter 'error' implicitly has an 'any' type, but a better type may be inferred from usage.ts(7044)
As explained by @AlekseyL. in the comments, it it usually but not always an Error object. A catch
clause requires that you catch any
or unknown
. You can check if it's an Error
with if (error instanceof Error)
.
An Error
is non-serializable. Ideally you would extract some properties from it in your saga or action creator rather than passing a non-serializable object in an action. It's easy to extract a string
.
catch (error: any) {
yield put(Actions.Error(String(error) || "An unknown error occurred"));
}
The string
conversion of an Error
object is like this:
String(new Error("some message"))
--> "Error: some message"
Here is a type-safe helper for converting an any
error to an object with name
and message
.
interface ErrorData {
name: string;
message: string;
}
const toError = (error: any): ErrorData => {
if (error instanceof Error) {
return {
name: error.name,
message: error.message
};
} else {
return {
name: "Error",
message: error?.toString() || "An unknown error occurred"
}
}
};