Is this code robust?

Hello, I’m trying to create a sign-up function which will test if there are any user accounts in the database with a given username and, if not, create a user. I have so far followed the approach of making the username prop unique in the database, and using try/catch statements to create the account. Here’s the code:

export async function createUser(email, username, password) {
	try {
		await client.query(
			q.Create('user', {
				data: {
					username: username,
					password: password,
					email: email,
				},
			})
		);
		return true;
	} catch (e) {
		return false;
	}
}

I was just wondering if this is good practice or if making the database send an error to my application whenever a user cannot be created is problematic for runtime, robustness, etc. Thank you

Hi,

As a general rule of thumb, yes, you should use try/catch blocks to handle any errors that come up. One suggestion I would make on this example, though, would be to do something more with the error statement, just in case it fails for some reason other than uniqueness:

    } catch (e) {
        return e;
    }

Caveat that it’s been a while since I’ve written any serious Java so you’ll want to tweak this return statement to be more useful. The point is, just returning false may not be sufficient to handle whatever went wrong. Examining the actual text of the error code would be more helpful.

Does this answer your question or is there anything else we can help with?

Cory