You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postman调用登录API返回500 Internal Server Error,但Spring Tools Suite控制台未显示错误信息

Hey there! Let's figure out how to get those missing error logs showing up in Spring Tools Suite (STS) so you can pinpoint exactly why your login API is throwing a 500 Internal Server Error. Here's a step-by-step approach to fix this:

1. Add Proper Logging to Your Service Layer

First, your current code throws an exception but doesn't log any details about what went wrong. Plus, you're repeatedly calling userRepo.findByEmail1() which is inefficient and risky (if the user record changes between calls, you might get unexpected behavior). Let's clean that up and add logging:

First, import the SLF4J logger at the top of your service class:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Then declare the logger inside your service class:

private static final Logger logger = LoggerFactory.getLogger(YourUserServiceImplClass.class); // Replace with your actual service class name

Now rewrite your login method to reduce redundant database calls and log errors:

@Override
public String login(LoginRequest request) {
    // Fetch user once to avoid repeated DB calls
    Optional<User> userOptional = userRepo.findByEmail(request.getEmail());
    
    if (userOptional.isPresent()) {
        User user = userOptional.get();
        
        if (passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            String token = UUID.randomUUID().toString();
            ConfirmationToken confirmationToken = new ConfirmationToken(
                    token,
                    LocalDateTime.now(),
                    LocalDateTime.now().plusMinutes(5),
                    user
            );
            confirmationTokenService.saveConfirmationToken(confirmationToken);
            t = confirmationToken.getExpiresAt();
            
            try {
                emailSender.send(user.getEmail(), buildEmail(user.getFirstName(), token));
            } catch (Exception e) {
                logger.error("Failed to send login confirmation email to {}", user.getEmail(), e);
                throw new IllegalStateException("Connexion réussie mais échec de l'envoi de l'email");
            }
            
            // Use StringBuilder for cleaner JSON construction
            StringBuilder response = new StringBuilder();
            response.append("{\n")
                    .append("\"text\": \"Utilisateur connecté avec succès, voici le token de connexion: ").append(token).append("\",\n")
                    .append("\"email\": \"").append(user.getEmail()).append("\",\n")
                    .append("\"Role\": \"").append(user.getRoles().toString()).append("\",\n")
                    .append("\"first_name\": \"").append(user.getFirstName()).append("\",\n")
                    .append("\"Enabled\": ").append(user.getEnabled()).append("\n}");
            return response.toString();
        } else {
            logger.error("Invalid password provided for email: {}", request.getEmail());
            throw new IllegalStateException("Les identifiants de connexion sont erronés");
        }
    } else {
        logger.error("No user found with email: {}", request.getEmail());
        throw new IllegalStateException("Les identifiants de connexion sont erronés");
    }
}

2. Add Exception Handling in Your Controller

Right now, if any unexpected exception occurs (like a failure in emailSender.send() or a database error), it'll bubble up as a 500 error without being logged. Let's add exception handling to catch and log these issues:

Update your controller method to wrap the service call in a try-catch block, and log full exception details:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api/v1/registration") // Make sure this matches your controller's base path
public class RegistrationController {

    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);

    // Constructor injection (preferred over @Autowired)
    public RegistrationController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping(path = "/connect")
    public ResponseEntity<String> login(@RequestBody LoginRequest request) {
        try {
            String response = userService.login(request);
            return ResponseEntity.ok(response);
        } catch (IllegalStateException e) {
            logger.error("Login validation failed: ", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("{\"error\": \"" + e.getMessage() + "\"}");
        } catch (Exception e) {
            // Catch-all for unexpected errors (e.g., DB issues, email service failures)
            logger.error("Unexpected internal error during login: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"error\": \"Une erreur interne est survenue\"}");
        }
    }
}

3. Verify Your Logging Configuration

Ensure your Spring Boot app is configured to output logs to STS. Check your application.properties or application.yml file:

For application.properties:

# Set root log level to INFO (adjust to DEBUG for more details)
logging.level.root=INFO
# Set debug logging for your application's package to see detailed logs
logging.level.com.your.package.name=DEBUG
# Enable debug logging for Spring Web to see request/response details
logging.level.org.springframework.web=DEBUG

For application.yml:

logging:
  level:
    root: INFO
    com.your.package.name: DEBUG
    org.springframework.web: DEBUG

Why This Works

  • Redundant DB Calls: Fetching the user once reduces database load and avoids potential inconsistencies.
  • Detailed Logs: The logger will now print exactly what went wrong (e.g., invalid password, missing user, email service failure) along with a full stack trace in STS.
  • Proper HTTP Status Codes: Instead of returning a generic 500 for invalid credentials, we return 401 Unauthorized, which is semantically correct.
  • Catch-All Exception Handling: Any unexpected errors (like database connection issues) will be logged with their full stack trace, making it easy to debug.

After making these changes, restart your app and test the login API again. You'll see detailed error logs in STS's console that will point you directly to the root cause of the 500 error.

内容的提问来源于stack exchange,提问作者Chahrazed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:12:45