应用全局异常抛出

This commit is contained in:
2025-05-14 12:54:02 +09:00
parent 8535dce094
commit 6a579104ba
2 changed files with 20 additions and 26 deletions

View File

@ -38,39 +38,26 @@ public class UserController {
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody RegistrationDto registrationDto) {
try {
UserEntity registeredUser = userService.registerNewUser(registrationDto);
UserEntity registeredUser = userService.registerNewUser(registrationDto);
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(registeredUser.getEmail()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.fail(ResultCode.BAD_REQUEST,null));
}
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(registeredUser.getEmail()));
}
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginDto loginDto) {
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String jwtToken = jwtService.generateToken(userDetails);
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Map<String, String> tokenResponse = new HashMap<>();
tokenResponse.put("token", jwtToken);
String jwtToken = jwtService.generateToken(userDetails);
return ResponseEntity.ok(ApiResponse.success(tokenResponse));
Map<String, String> tokenResponse = new HashMap<>();
tokenResponse.put("token", jwtToken);
} catch (BadCredentialsException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.fail(ResultCode.UNAUTHORIZED,null));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.fail(ResultCode.SERVICE_UNAVAILABLE,null));
}
return ResponseEntity.ok(ApiResponse.success(tokenResponse));
}
}