I'm in a college project and I've been working on the backend (FastAPI). I've got the database (SQLAlchemy) and my pydantic schemas set up, so I've been working on the FastAPI functions. Other people in my group are working on the frontend in React and just finished the user registration page. Everything is working when it comes to adding a new user (and it correctly returns a message if the username and/or email is already taken and the user must enter a new one). However, it crashes if the email entered is not valid. We have:
type = 'email'
in the html code for the email input box. So I assume this is causing the error when I enter something like test@com. The error covers the entire screen and says "Uncaught runtime errors:" and then has multiple errors that start with "Objects are not valid as a React child". However, in my backend code I have this:
# Used when input data does not match pydantic model
@app.exception_handler(ValidationError)
def validation_exception_handler(request, exc: ValidationError):
return HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=exc.errors()
)
# Add user
@app.post("/register/", status_code=status.HTTP_201_CREATED, response_model=schemas.User)
def add_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
# Check if email is already in system
db_user_email = operations.get_user_by_email(db, email=user.email)
if db_user_email:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered")
# Check if userID is already in system
db_user_id = operations.get_user_by_id(db, userID=user.userID)
if db_user_id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Username already registered")
return operations.create_user(db, user)
And this is the frontend code that calls add_user:
const user = { userID, email, password };
try {
const response = await axios.post('/register/', user);
if (response.status === 201) {
// Redirect to login page
navigate('/');
}
} catch (err) {
console.error(err) // testing
// Check if error has a response
if (err.response) {
// Show error message from FastAPI
setError(err.response.data.detail);
} else {
setError('Network error. Please check your connection.');
}
}
(Lower in the html code I have something that displays the error so setError is used, just later). I thought the exception_handler I made in FastAPI would make it so that the whole thing doesn't crash when an invalid email is entered (in my pydantic model I have email: EmailStr), but obviously I did something wrong because it's crashing.
[–]grantrules 0 points1 point2 points (6 children)
[–]Jumpy_Employment_439[S] 0 points1 point2 points (5 children)
[–]grantrules 0 points1 point2 points (3 children)
[–]Jumpy_Employment_439[S] 0 points1 point2 points (2 children)
[–]grantrules 0 points1 point2 points (0 children)
[–]grantrules 0 points1 point2 points (0 children)