Spring 글로벌 예외 처리의 세 가지 방법 이해
이런 방식을 사용하면 통합이 간단하고 좋은 확장성, 기존 코드에 대한 침입성이 없다는 장점이 있지만 이 방법은 이상 정보만 얻을 수 있고 이상이 발생할 때 이상을 제외한 데이터를 얻어야 하는 경우에는 적용되지 않는다.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.balbala.mvc.web"})
public class WebMVCConfig extends WebMvcConfigurerAdapter{
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver()
{
SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "page-404");
mappings.put("org.springframework.dao.DataAccessException", "data-access");
mappings.put("org.springframework.transaction.TransactionException", "transaction-Failure");
b.setExceptionMappings(mappings);
return b;
}
}
(2) HandlerExceptionResolver첫 번째에 비해 HandlerExceptionResolver는 정의된 이상 처리 페이지를 정확하게 표시하여 통일 이상 처리의 목표를 달성할 수 있다
1. 클래스를 정의하여 HandlerExceptionResolver 인터페이스를 실현하고 이번에는 자신의 이전 코드를 붙인다
package com.athena.common.handler;
import com.athena.common.constants.ResponseCode;
import com.athena.common.exception.AthenaException;
import com.athena.common.http.RspMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by sam on 15/4/14.
*/
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(GlobalHandlerExceptionResolver.class);
/**
*
*/
@Override
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception ex) {
ex.printStackTrace();
if (ex instanceof AthenaException) {
//AthenaException
ex.printStackTrace();
printWrite(ex.toString(), resp);
return new ModelAndView();
}
//RspMsg
//ResponseCode
RspMsg unknownException = null;
if (ex instanceof NullPointerException) {
unknownException = new RspMsg(ResponseCode.CODE_UNKNOWN, " ", null);
} else {
unknownException = new RspMsg(ResponseCode.CODE_UNKNOWN, ex.getMessage(), null); }
printWrite(unknownException.toString(), resp);
return new ModelAndView();
}
/**
* response
*
* @param msg
* @param response
* @throws IOException
*/
public static void printWrite(String msg, HttpServletResponse response) {
try {
PrintWriter pw = response.getWriter();
pw.write(msg);
pw.flush();
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 스프링 설정에 추가, 여기에 관련 부분만 붙였습니다
import com.athena.common.handler.GlobalHandlerExceptionResolver;
import org.springframework.context.annotation.Bean;
import com.athena.common.handler.GlobalHandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by sam on 15/4/14.
*/
public class WebSpringMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public GlobalHandlerExceptionResolver globalHandlerExceptionResolver() {
return new GlobalHandlerExceptionResolver();
}
}
(3) @ExceptionHandler이것은 필자의 현재 항목의 사용 방식이며, 여기에도 관련 부분만 붙였다
1. 먼저 부류를 정의하고 기초적인 방법을 실현한다
package com.balabala.poet.base.spring;
import com.google.common.base.Throwables;
import com.raiyee.poet.base.exception.MessageException;
import com.raiyee.poet.base.utils.Ajax;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
public class BaseGlobalExceptionHandler {
protected static final Logger logger = null;
protected static final String DEFAULT_ERROR_MESSAGE = " , ";
protected ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e, String viewName, HttpStatus status) throws Exception {
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
throw e;
String errorMsg = e instanceof MessageException ? e.getMessage() : DEFAULT_ERROR_MESSAGE;
String errorStack = Throwables.getStackTraceAsString(e);
getLogger().error("Request: {} raised {}", req.getRequestURI(), errorStack);
if (Ajax.isAjax(req)) {
return handleAjaxError(rsp, errorMsg, status);
}
return handleViewError(req.getRequestURL().toString(), errorStack, errorMsg, viewName);
}
protected ModelAndView handleViewError(String url, String errorStack, String errorMessage, String viewName) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", errorStack);
mav.addObject("url", url);
mav.addObject("message", errorMessage);
mav.addObject("timestamp", new Date());
mav.setViewName(viewName);
return mav;
}
protected ModelAndView handleAjaxError(HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
rsp.setCharacterEncoding("UTF-8");
rsp.setStatus(status.value());
PrintWriter writer = rsp.getWriter();
writer.write(errorMessage);
writer.flush();
return null;
}
public Logger getLogger() {
return LoggerFactory.getLogger(BaseGlobalExceptionHandler.class);
}
}
2. 당신이 포착해야 할 이상에 대응하는 처리 방식
package com.balabala.poet.base.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class GlobalExceptionHandler extends BaseGlobalExceptionHandler {
// 404
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handle404Error(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
return handleError(req, rsp, e, "error-front", HttpStatus.NOT_FOUND);
}
//500
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
return handleError(req, rsp, e, "error-front", HttpStatus.INTERNAL_SERVER_ERROR);
}
//TODO
//TRY NOW!!!
@Override
public Logger getLogger() {
return LoggerFactory.getLogger(GlobalExceptionHandler.class);
}
}
이상은 세 가지 처리 방식입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.