1

I'm encountering an error while running my API server using Ntex:

Error Message:

App state is not configured, to configure use App::state()

I have already configured the application state using App::state(), but the error persists.


My Setup:

My server configuration is as follows

#[ntex::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();

    let pool = Arc::new(Mutex::new(database::establish_connection()));
    let addr = SocketAddr::from(([0, 0, 0, 0], 8082));

    let user_repository = Arc::new(Mutex::new(UserRepository::new(pool.clone())));
    let user_service = UserService::new(user_repository);

    HttpServer::new(move || {
        App::new()
            .state(user_service.clone())
            .service(handle_login)
            .service(handle_register)
            .wrap(Logger::default())
    })
    .bind(addr)?
    .run()
    .await
}

Here’s a link to my server configuration in main.rs:
GitHub Link to Code

Image Reference:

Error Screenshot


Steps to Reproduce:

  1. Clone the repository: mt-auth-service.

  2. Run the server using cargo run.

  3. Attempt to hit the /login endpoint (or any other endpoint).


Expected Behavior:

The server should process the request and return the appropriate response.


Actual Behavior:

The server throws the error mentioned above when processing the request.


Additional Information:

  • I was able to add data to the database earlier.

  • The error started occurring after refactoring my code.

Any insights into why this might be happening or how to debug it further would be greatly appreciated!

Initially, my UserService struct was defined like this:

struct UserService {             
    repo: UserRepository,  
}

To address the issue, I refactored it to use a thread-safe wrapper:

struct UserService {
    repo: Arc<Mutex<UserRepository>>, 
}

I made a similar change to the UserRepository struct as well, wrapping its dependencies in Arc<Mutex<...>>.

Despite these changes, the error persists.

2 Answers 2

1

Fix the app state type in the request handlers:

#[web::post("/login")]
pub async fn handle_login(
-    service: web::types::State<Arc<Mutex<UserService>>>,
+    service: web::types::State<UserService>,
    req: Json<UserLoginRequest>,
) -> impl Responder {
    // ...
}

There are different types in the request handlers and in the app initialization: Arc<Mutex<UserService>> != UserService.

Sign up to request clarification or add additional context in comments.

Comments

-1

The error has been fixed as my imports were incorrect , I was not using use crate::controllers.., I was directly importing use controllers::.., The working code is at this commit

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.