|
| 1 | +package com.codingapi.springboot.framework.servlet; |
| 2 | + |
| 3 | + |
| 4 | +import com.codingapi.springboot.framework.exception.LocaleMessageException; |
| 5 | +import jakarta.servlet.http.HttpServletRequest; |
| 6 | +import jakarta.servlet.http.HttpServletResponse; |
| 7 | +import lombok.extern.slf4j.Slf4j; |
| 8 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; |
| 9 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
| 10 | +import org.springframework.context.annotation.Bean; |
| 11 | +import org.springframework.context.annotation.Configuration; |
| 12 | +import org.springframework.web.servlet.HandlerExceptionResolver; |
| 13 | +import org.springframework.web.servlet.ModelAndView; |
| 14 | +import org.springframework.web.servlet.view.json.MappingJackson2JsonView; |
| 15 | + |
| 16 | +@Configuration |
| 17 | +@ConditionalOnClass(name = "org.springframework.web.servlet.HandlerExceptionResolver") |
| 18 | +public class BasicHandlerExceptionResolverConfiguration { |
| 19 | + |
| 20 | + @Bean |
| 21 | + @ConditionalOnMissingBean |
| 22 | + public HandlerExceptionResolver servletExceptionHandler() { |
| 23 | + return new ServletExceptionHandler(); |
| 24 | + } |
| 25 | + |
| 26 | + @Slf4j |
| 27 | + public static class ServletExceptionHandler implements HandlerExceptionResolver { |
| 28 | + |
| 29 | + private final static String DEFAULT_ERROR_CODE = "system.err"; |
| 30 | + |
| 31 | + @Override |
| 32 | + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { |
| 33 | + MappingJackson2JsonView view = new MappingJackson2JsonView(); |
| 34 | + ModelAndView mv = new ModelAndView(view); |
| 35 | + mv.addObject("success", false); |
| 36 | + if (ex instanceof LocaleMessageException) { |
| 37 | + LocaleMessageException localMessageException = (LocaleMessageException) ex; |
| 38 | + mv.addObject("errCode", localMessageException.getErrCode()); |
| 39 | + mv.addObject("errMessage", localMessageException.getMessage()); |
| 40 | + log.warn("controller errCode:{} exception:{}", localMessageException.getErrCode(), ex.getLocalizedMessage()); |
| 41 | + return mv; |
| 42 | + } |
| 43 | + log.warn("controller exception:{}", ex.getLocalizedMessage(), ex); |
| 44 | + mv.addObject("errCode", DEFAULT_ERROR_CODE); |
| 45 | + mv.addObject("errMessage", ex.getMessage()); |
| 46 | + |
| 47 | + return mv; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments