이 기사에서는 Spring Cloud Gateway의 전역 예외 처리(코드 예제)에 대해 소개합니다. 이는 특정 참조 가치가 있으므로 도움이 필요한 친구에게 도움이 되기를 바랍니다.
Spring Cloud Gateway의 전역 예외 처리는 @ControllerAdvice를 사용하여 직접 처리할 수 없습니다. 발생한 예외 정보를 추적하여 해당 소스 코드를 찾고 비즈니스 요구 사항에 맞게 일부 처리 논리를 사용자 정의하세요.
게이트웨이는 인터페이스의 프록시 전달자이고 백엔드는 REST API에 해당하며 반환 데이터 형식은 JSON입니다. 처리가 이루어지지 않은 경우 예외가 발생하면 게이트웨이에서 제공하는 기본 오류 메시지는 프런트 엔드에서 예외를 처리하기에는 불편한 페이지입니다.
예외 정보를 처리하고 JSON 형식의 데이터를 클라이언트에 반환해야 합니다. 먼저 구현된 코드를 살펴보고, 그다음 주의할 점을 알려드리겠습니다.
사용자 정의된 예외 처리 논리:
package com.cxytiandi.gateway.exception; import java.util.HashMap; import java.util.Map; import org.springframework.boot.autoconfigure.web.ErrorProperties; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; /** * 自定义异常处理 * * <p>异常时用JSON代替HTML异常信息</p><p> * * @author yinjihuan * */ public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler { public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) { super(errorAttributes, resourceProperties, errorProperties, applicationContext); } /** * 获取异常属性 */ @Override protected Map<string> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { int code = 500; Throwable error = super.getError(request); if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) { code = 404; } return response(code, this.buildMessage(request, error)); } /** * 指定响应处理方法为JSON处理的方法 * @param errorAttributes */ @Override protected RouterFunction<serverresponse> getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); } /** * 根据code获取对应的HttpStatus * @param errorAttributes */ @Override protected HttpStatus getHttpStatus(Map<string> errorAttributes) { int statusCode = (int) errorAttributes.get("code"); return HttpStatus.valueOf(statusCode); } /** * 构建异常信息 * @param request * @param ex * @return */ private String buildMessage(ServerRequest request, Throwable ex) { StringBuilder message = new StringBuilder("Failed to handle request ["); message.append(request.methodName()); message.append(" "); message.append(request.uri()); message.append("]"); if (ex != null) { message.append(": "); message.append(ex.getMessage()); } return message.toString(); } /** * 构建返回的JSON数据格式 * @param status 状态码 * @param errorMessage 异常信息 * @return */ public static Map<string> response(int status, String errorMessage) { Map<string> map = new HashMap(); map.put("code", status); map.put("message", errorMessage); map.put("data", null); return map; } }</string></string></string></serverresponse></string></p>
기본 구성 재정의:
package com.cxytiandi.gateway.exception; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.result.view.ViewResolver; /** * 覆盖默认的异常处理 * * @author yinjihuan * */ @Configuration @EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class}) public class ErrorHandlerConfiguration { private final ServerProperties serverProperties; private final ApplicationContext applicationContext; private final ResourceProperties resourceProperties; private final List<viewresolver> viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer; public ErrorHandlerConfiguration(ServerProperties serverProperties, ResourceProperties resourceProperties, ObjectProvider<list>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) { this.serverProperties = serverProperties; this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList); this.serverCodecConfigurer = serverCodecConfigurer; } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) { JsonExceptionHandler exceptionHandler = new JsonExceptionHandler( errorAttributes, this.resourceProperties, this.serverProperties.getError(), this.applicationContext); exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders()); return exceptionHandler; } }</list></viewresolver>
Notes
- 예외 발생 시 HTML 대신 JSON을 반환하는 방법은 무엇입니까?
org.springframework.boot.autoconfigure.web.reactive에서. error .DefaultErrorWebExceptionHandler의 getRoutingFunction() 메서드는 반환 형식을 제어합니다. 원래 코드는 다음과 같습니다.
@Override protected RouterFunction<serverresponse> getRoutingFunction( ErrorAttributes errorAttributes) { return RouterFunctions.route(acceptsTextHtml(), this::renderErrorView) .andRoute(RequestPredicates.all(), this::renderErrorResponse); }</serverresponse>
여기서 우선순위는 HTML로 표시하는 것입니다.
protected RouterFunction<serverresponse> getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); }</serverresponse>
- getHttpStatus를 재설정해야 합니다.
의 원래 작성 방법은 상태를 통해 해당 HttpStatus를 얻는 것입니다. 코드는 다음과 같습니다.
protected HttpStatus getHttpStatus(Map<string> errorAttributes) { int statusCode = (int) errorAttributes.get("status"); return HttpStatus.valueOf(statusCode); }</string>
우리가 정의한 형식에 상태 필드가 없으면 오류가 발생합니다. 보고했는데 해당 응답 코드를 찾을 수 없거나 데이터가 반환됩니다. 형식에 상태 하위 섹션을 추가하거나 다시 작성하세요. 여기서 반환하는 것은 코드이므로 코드를 다시 작성해야 합니다.
@Override protected HttpStatus getHttpStatus(Map<string> errorAttributes) { int statusCode = (int) errorAttributes.get("code"); return HttpStatus.valueOf(statusCode); }</string>
위 내용은 Spring Cloud Gateway의 전역 예외 처리 소개(코드 예)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

javaispopularforcross-platformdesktopapplicationsduetoits "writeonce, runanywhere"철학

Java에서 플랫폼 별 코드를 작성하는 이유에는 특정 운영 체제 기능에 대한 액세스, 특정 하드웨어와 상호 작용하고 성능 최적화가 포함됩니다. 1) JNA 또는 JNI를 사용하여 Windows 레지스트리에 액세스하십시오. 2) JNI를 통한 Linux 특이 적 하드웨어 드라이버와 상호 작용; 3) 금속을 사용하여 JNI를 통해 MacOS의 게임 성능을 최적화하십시오. 그럼에도 불구하고 플랫폼 별 코드를 작성하면 코드의 이식성에 영향을 미치고 복잡성을 높이며 잠재적으로 성능 오버 헤드 및 보안 위험을 초래할 수 있습니다.

Java는 Cloud-Native Applications, Multi-Platform 배포 및 교차 운용성을 통해 플랫폼 독립성을 더욱 향상시킬 것입니다. 1) Cloud Native Applications는 Graalvm 및 Quarkus를 사용하여 시작 속도를 높입니다. 2) Java는 임베디드 장치, 모바일 장치 및 양자 컴퓨터로 확장됩니다. 3) Graalvm을 통해 Java는 Python 및 JavaScript와 같은 언어와 완벽하게 통합되어 언어 교차 수용 가능성을 향상시킵니다.

Java의 강력한 유형 시스템은 유형 안전, 통합 유형 변환 및 다형성을 통해 플랫폼 독립성을 보장합니다. 1) 유형 안전성 런타임 오류를 피하기 위해 컴파일 시간에 유형 검사를 수행합니다. 2) 통합 유형 변환 규칙은 모든 플랫폼에서 일관성이 있습니다. 3) 다형성 및 인터페이스 메커니즘은 코드가 다른 플랫폼에서 일관되게 행동하게 만듭니다.

JNI는 Java의 플랫폼 독립성을 파괴 할 것입니다. 1) JNI는 특정 플랫폼에 대한 로컬 라이브러리를 요구합니다. 2) 대상 플랫폼에서 로컬 코드를 컴파일하고 연결해야합니다. 3) 운영 체제 또는 JVM의 다른 버전은 다른 로컬 라이브러리 버전을 필요로 할 수 있습니다.

신흥 기술은 위협을 일으키고 Java의 플랫폼 독립성을 향상시킵니다. 1) Docker와 같은 클라우드 컴퓨팅 및 컨테이너화 기술은 Java의 플랫폼 독립성을 향상 시키지만 다양한 클라우드 환경에 적응하도록 최적화되어야합니다. 2) WebAssembly는 Graalvm을 통해 Java 코드를 컴파일하여 플랫폼 독립성을 확장하지만 성능을 위해 다른 언어와 경쟁해야합니다.

다른 JVM 구현은 플랫폼 독립성을 제공 할 수 있지만 성능은 약간 다릅니다. 1. OracleHotspot 및 OpenJDKJVM 플랫폼 독립성에서 유사하게 수행되지만 OpenJDK에는 추가 구성이 필요할 수 있습니다. 2. IBMJ9JVM은 특정 운영 체제에서 최적화를 수행합니다. 3. Graalvm은 여러 언어를 지원하며 추가 구성이 필요합니다. 4. AzulzingJVM에는 특정 플랫폼 조정이 필요합니다.

플랫폼 독립성은 여러 운영 체제에서 동일한 코드 세트를 실행하여 개발 비용을 줄이고 개발 시간을 단축시킵니다. 구체적으로, 그것은 다음과 같이 나타납니다. 1. 개발 시간을 줄이면 하나의 코드 세트 만 필요합니다. 2. 유지 보수 비용을 줄이고 테스트 프로세스를 통합합니다. 3. 배포 프로세스를 단순화하기위한 빠른 반복 및 팀 협업.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
