Привет, я новичок в Spring и Angular. Я создаю Java-сервер Spring и угловой клиент.По сути, я хочу, чтобы клиент мог отлавливать исключение, выбрасываемое с сервера.Я определил класс CustomExeption.java и у меня есть CustomRestExcepotionHandler.java на стороне сервера.Прямо сейчас я не уверен, где я должен выбросить исключение на сервере для клиента, чтобы поймать.
Я следовал учебному пособию: https://www.baeldung.com/global-error-handler-in-a-spring-rest-api
Теперь он возвращает мне 500 ВнутреннихСообщение об ошибке сервера на стороне клиента в HttpErrorResponse.
Я хочу, чтобы оно возвратило мое сообщение об обычном исключении.Может ли кто-нибудь помочь мне увидеть, есть ли проблемы на стороне сервера.почему HttpErrorResponse не перехватывает исключение CustomException?Спасибо!
public class ApiError {
private HttpStatus status;
private String message;
private List<String> errors;
public ApiError(HttpStatus status, String message, List<String> errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public ApiError(HttpStatus status, String message, String error) {
super();
this.status = status;
this.message = message;
errors = Arrays.asList(error);
}
public HttpStatus getStatus() {
// TODO Auto-generated method stub
return status;
}
public String getMessage() {
// TODO Auto-generated method stub
return message;
}
}
---
-------------------- ExceptionHandler
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
HttpStatus status, WebRequest request) {
ApiError apiError =
new ApiError(status, ex.getMessage(), ex.getMessage());
return handleExceptionInternal(
ex, apiError, headers, apiError.getStatus(), request);
}
protected ResponseEntity<Object> handleResponseStatusException(ResponseStatusException ex,Object body, HttpHeaders headers,
HttpStatus status, WebRequest request ){
ApiError apiError =
new ApiError(status, ex.getMessage(), ex.getMessage());
return handleExceptionInternal(
ex, apiError, headers, apiError.getStatus(), request);
}
}
public ResponseEntity<AtlasJWT> signInUser(String userName, String password) {String userId = "(uid=" + userName + ")";
if (ldapTemplate.authenticate("", userId, password)) {
log.info("ldapTemplate.authenticate returned true");
Optional<AtlasUser> optLoggedInUser = userRepository.findByUsername(userName);
AtlasJWT atlasJwtToken = jwtTokenProvider.createAtlasJwtToken(optLoggedInUser.get());
if (optLoggedInUser.isPresent()) {
log.info("Atlas JWT: {}", atlasJwtToken);
return new ResponseEntity<AtlasJWT>(atlasJwtToken, HttpStatus.OK);
} else {
//ApiError error = new ApiError(HttpStatus.BAD_REQUEST,"No such User found in the Atlas Database","No such User found in the Atlas Database");
throw new CustomException("No such User found in the Atlas Database",HttpStatus.FORBIDDEN);
}
} else {
//ApiError error = new ApiError(HttpStatus.FORBIDDEN,"Invalid username/password supplied","Invalid username/password supplied");
throw new CustomException("Invalid username/password supplied", HttpStatus.FORBIDDEN);
}
}
Мой компонент входа на стороне клиента, как показано ниже:
login(username: string, password: string) {
console.log('Inside AuthenticationService. Username: ', username);
// const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;
const body = {
'username': username,
'password': password
};
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
console.log('Invoking server authentication for username', username);
return this.http.post<AtlasJWT>('/auth/api/signin', body, httpOptions).pipe(catchError(this.handleError));
}
private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = '';
if (err.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = err.message;
// console.log(err);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.log(err);
}
console.error(errorMessage);
return throwError(errorMessage);
}