Handling Rejections
Rejection
π¨βπΌ Our API sometimes fails, and we need to handle those failures gracefully.
Rejected Promises should be caught so we can return a friendly error state.
π¨ Open
and:
- Keep
fetchUser(id)as provided:id === '1'resolves to Alice (id: '1',name: 'Alice',email: 'alice@example.com')- any other id rejects with
Error('User not found')
- Update
getUserProfile(id)to handle rejections with.catch() - Return shapes:
- success:
{ status: 'success', user } - error:
{ status: 'error', message }wheremessageiserror.messagewhen the rejection is anError, otherwise'Unknown error'
- success:
- Export both
fetchUserandgetUserProfile
Completion checks:
await getUserProfile('1')β{ status: 'success', user: { id: '1', ... } }await getUserProfile('missing')β{ status: 'error', message: 'User not found' }await fetchUser('missing')still rejects (do not swallow that rejection insidefetchUseritself)