W
Wasp3mo ago
cmilazzo

Error handling in actions

How do you safely throw an exception from an action without crashing the server but make sure to notify the client?
1 Reply
kapa.ai
kapa.ai3mo ago
Hi @cmilazzo. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- In Wasp, for security reasons, all exceptions thrown in the Action's NodeJS implementation are sent to the client as responses with the HTTP status code 500, with all other details removed. This helps against accidentally leaking possibly sensitive information over the network. However, if you want to pass additional error information to the client, you can construct and throw an appropriate HttpError in your implementation. Here is an example in JavaScript and TypeScript: JavaScript:
import { HttpError } from 'wasp/server'

export const createTask = async (args, context) => {
throw new HttpError(
403, // status code
"You can't do this!", // message
{ foo: 'bar' } // data
)
}
import { HttpError } from 'wasp/server'

export const createTask = async (args, context) => {
throw new HttpError(
403, // status code
"You can't do this!", // message
{ foo: 'bar' } // data
)
}
TypeScript:
import { type CreateTask } from 'wasp/server/operations'
import { HttpError } from 'wasp/server'

export const createTask: CreateTask = async (args, context) => {
throw new HttpError(
403, // status code
"You can't do this!", // message
{ foo: 'bar' } // data
)
}
import { type CreateTask } from 'wasp/server/operations'
import { HttpError } from 'wasp/server'

export const createTask: CreateTask = async (args, context) => {
throw new HttpError(
403, // status code
"You can't do this!", // message
{ foo: 'bar' } // data
)
}
If the status code is 4xx, the client will receive a response object with the corresponding message and data fields, and it will rethrow the error (including these fields). To prevent information leakage, the server won't forward these fields for any other HTTP status codes. For more details, you can refer to the Wasp documentation (https://wasp-lang.dev/docs/data-model/operations/actions#error-handling). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @cmilazzo, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Want results from more Discord servers?
Add your server