要从Spring Boot中获取异常文本,可以通过以下步骤使用Angular:
@ExceptionHandler
注解来处理异常,并将异常消息放入响应体中。@RestController
public class MyController {
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(Exception ex) {
String errorMessage = "An error occurred: " + ex.getMessage();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage);
}
// 其他控制器方法
}
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
export class MyComponent {
constructor(private http: HttpClient) {}
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// 客户端错误
console.error('An error occurred:', error.error.message);
} else {
// 服务器端错误
console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
}
}
getData() {
this.http.get('/api/data').subscribe(
response => {
// 处理成功响应
},
error => {
this.handleError(error);
}
);
}
}
在上面的代码中,handleError
方法用于处理错误响应。如果是客户端错误,可以直接从error.error.message
中获取异常消息。如果是服务器端错误,可以从error.status
和error.error
中获取响应的状态码和异常消息。
Error: {{ errorMessage }}
在上面的代码中,errorMessage
是在组件中定义的一个变量,用于存储异常消息。当发生错误时,可以将异常消息赋值给errorMessage
变量,并在模板中显示出来。
这样,你就可以通过Angular从Spring Boot中获取并显示异常文本了。
下一篇:Angular从提供者获取数据