Web
Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest
docs.spring.io
틀린 내용은 알려주시면 감사합니다 🐥
1.1.10. Error Handling
기본적으로 Spring Boot 는 모든 오류를 처리하는 /error 매핑을 제공하고 있고, Servlet container 에 "global" 오류 페이지로 등록되어있다.
machine client 일 경우에 오류에 대한 details, HTTP 상태 및 exception message가 포함된 JSON response를 생성해준다.
browser client 일 경우 동일한 데이터를 HTML형식으로 렌더링 해주는 "whitelabel" 오류로 보여준다. 사용자 지정도 물론 가능하다 error view를 resolve하면 된다
default error handling 을 사용자 지정하려고 하는 경우 server.error properties 를 지정할 수 있다.
Common Application Properties
docs.spring.io
아예 기본 동작을 완전히 대체하려면 ErrorController 를 구현하여 원하는 유형에 bean 정의를 등록하거나 기존 메커니즘에서 내용만 대체하는 ErrorAttributes type 빈을 추가할 수 있다
BasicErrorController는 사용자 지정 ErrorController의 기본 클래스로 사용할 수 있다.
이는 new content type에 대한 handler를 추가하려는 경우에 특히 유용하다(기본값은 text/html을 처리하고 다른 모든 항목에 대한 폴백을 제공).
이렇게 하려면 BasicErrorController를 extend하고, @RequestMapping이 포함된 공용 method 추가하고, 새 type의 빈을 만듭니다.
Spring MVC는 Media type 으로 application/problem+json 이용하여 오류 메세지를 생성할 수 있다
{
"type": "https://example.org/problems/unknown-project",
"title": "Unknown project",
"status": 404,
"detail": "No project found for id 'spring-unknown'",
"instance": "/projects/spring-unknown"
}
spring.mvc.problemdetails.enabled를 true 로 활성화시키면 된다
원하는 특정 controller 또는 exception type 유형을 반환할 수 있도록 @ControllerAdvice 애노테이션을 붙여 정의할 수 있다
@ControllerAdvice(basePackageClasses = SomeController.class)
public class MyControllerAdvice extends ResponseEntityExceptionHandler {
@ResponseBody
@ExceptionHandler(MyException.class)
public ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new MyErrorBody(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
HttpStatus status = HttpStatus.resolve(code);
return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
}
}
SomeController 와 동일한 패키지에서 정의된 controllerdp 의해 MyException이 발생하면,
기존의 ErrorAttributes representation 대신 MyErrorBody 에서 지정한 POJO JSON이 사용된다
경우에 따라 controller 수준에서 처리되는 오류가 metrics infrastructure 에 의해 기록되지 않는다
애플리케이션은 처리된 예외 요청 속성으로 설정한 뒤, 요청 metric 과 함께 기록되도록 할 수 있다
이렇게 하면 된다
@Controller
public class MyController {
@ExceptionHandler(CustomException.class)
String handleCustomException(HttpServletRequest request, CustomException ex) {
request.setAttribute(ErrorAttributes.ERROR_ATTRIBUTE, ex);
return "errorView";
}
}
Custom Error Pages
주어진 status code 에 따라 원하는 오류 페이지를 표시하려면 /error 디렉토리에 파일을 추가하면 된다
오류페이지는 static HTML(static rsouce directories) 이나 템플릿을 사용하여 작성할 수 있고
파일 이름은 exact status code 또는 series mask 여야한다
404
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
5xx번대 모두 (난 freemarker 안써서 그냥 html로 예제 바꿈)
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 5xx.html
+- <other public assets>
또 이렇게 복합한 매핑에서 ErrorViewResolver 로 구현할 수도 있다
public class MyErrorViewResolver implements ErrorViewResolver {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
// Use the request or status to optionally return a ModelAndView
if (status == HttpStatus.INSUFFICIENT_STORAGE) {
// We could add custom model values here
new ModelAndView("myview");
}
return null;
}
}
You can also use regular Spring MVC features such as @ExceptionHandler methods and @ControllerAdvice. T
he ErrorController then picks up any unhandled exceptions.
내가 정리한 ExceptionHandler
https://delightpip.tistory.com/45
[Spring framework Web MVC docs] 1.1.8. Exceptions
틀린 해석이 있다면 알려주세요 https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-exceptionhandlers Web on Servlet Stack Spring Web MVC is the original web framework built on the Servlet API and has been included i
delightpip.tistory.com
내가 정리한 ControllerAdvice
https://delightpip.tistory.com/38
[Spring framework Web MVC docs] 1.3.7 ControllerAdvice
틀린 해석이 있다면 알려주세요 @ControllerAdvice 는 @Controller 가 있는 모든 곳에 initbinder, exceptionhandler, modelattribute를 어떻게 작업할지 미리 선언해준다 공통분모 같은?? @Controller 안에 @ExceptionHandler,
delightpip.tistory.com
Mapping Error Pages Outside of Spring MVC
이건 Spring MVC 사용하지않는 애플리케이션의 경우 ErrorPageRegistrar 인터페이스를 사용하여 ErrorPages 등록하는 방법이다
이 abstraction는 기본 embedded servlet container에서 직접 작동하기 때문에
Spring MVC DispatcherServlet이 없는 경우에도 작동한다
@Configuration(proxyBeanMethods = false)
public class MyErrorPagesConfiguration {
@Bean
public ErrorPageRegistrar errorPageRegistrar() {
return this::registerErrorPages;
}
private void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
}
}
Filter에 의해 처리되는 경로로 ErrorPage를 등록하는 경우(as is common with some non-Spring web frameworks, like Jersey and Wicket) Filter는 다음과 같이 명시적으로 ERROR Dispatcher로 등록되어야 한다
@Configuration(proxyBeanMethods = false)
public class MyFilterConfiguration {
@Bean
public FilterRegistrationBean<MyFilter> myFilter() {
FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(new MyFilter());
// ...
registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
return registration;
}
}
ERROR dispatcher type은 기본 FilterRegistrationBean 에는 포함되어있지 않다
Error Handling in a WAR Deployment
When deployed to a servlet container, Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. This is necessary as the servlet specification does not provide an API for registering error pages. Depending on the container that you are deploying your war file to and the technologies that your application uses, some additional configuration may be required.
The error page filter can only forward the request to the correct error page if the response has not already been committed. By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet’s service method. You should disable this behavior by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false.
'Web > spring' 카테고리의 다른 글
[Spring Framework Core] 4.3. Language Reference (2) (0) | 2023.02.23 |
---|---|
[Spring Framework Core] 4.3. Language Reference (1) (0) | 2023.02.22 |
[Spring Framework integration] 1. REST Clients (0) | 2023.02.19 |
[Spring Security] Spring MVC Integration (0) | 2023.02.19 |
[Spring framework Web MVC docs] 1.10. HTTP Caching (0) | 2023.02.18 |