SpringBoot 예외 처리 방법
                                            
 4391 단어  프레임
                    
SpringBoot 예외 처리 방식:  
방식 1: 사용자 정의 오류 인터페이스
  
SpringBoot 기본 비정상 처리 메커니즘: SpringBoot 기본값은 이미 비정상 처리 메커니즘을 제공합니다.프로그램에 이상이 생기면 SpringBoot은/error의 URL처럼 요청을 보냅니다.springBoot에서/error 요청을 처리하기 위해 Basic Exception Controller를 제공합니다. 그리고 모든 이상을 사용자 정의 오류 페이지로 이동해야 한다면 src/main/resources/templates 디렉터리에서 error를 만들어야 합니다.html 페이지.
    
 
 
  
방식 2: @ExceptionHandle 메모 처리 예외
  @Controller
public class Demo01Controller {
    @RequestMapping("/demo01")
    public String showInfo1(){
        String str = null;
        //      
        str.length();
        return "index";
    }
    @RequestMapping("/demo02")
    public String showInfo2(){
        int a = 10 / 0 ;
        return "index";
    }
    /**
     *   java.lang.ArithmeticException
     *   ModelAndView: 
     *  
     * @param  e   Exception e: 
     * @return
     */
    @ExceptionHandler(value = {java.lang.ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
    /**
     *   NullPointException  
     * @param e
     * @return
     */
   @ExceptionHandler(value = {NullPointerException.class})
    public ModelAndView nullpointException(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error",e.toString());
        mv.setViewName("error2");
        return mv;
    }
  
페이지 정보:
error1.html 
    
     -ArithmeticException  
    ArithmeticException
   
  
error2.html 
    
     -NullPointerException   
     NullPointerException
   
  
방식 3: @ControllerAdvice+@ExceptionHandler 메모 처리 예외
  /**
 *       @ControllerAdvice
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class Global01Exception {
    /**
     *  
     * @param e
     * @return
     */
    @ExceptionHandler(value = {java.lang.NullPointerException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
}
  
방식 4: SimpleMappingExceptionResolver 처리 예외 구성
  /**
 * @desc    SimpleMappingExceptionResolver  
 */
@Configuration  
public class Global02Exception {
    /**
     *      SimpleMappingExceptionResolver
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        /**
         *  1     
         *  2  
         */
        mappings.put("java.lang.NullPointerException", "error1");
        mappings.put("java.lang.ArithmeticException", "error2");
        // 
        resolver.setExceptionMappings(mappings);
        return resolver;
    }
}
  
방식 5: 사용자 정의 HandlerExceptionResolver 클래스 처리 예외
  /**
 * @desc    HandlerExceptionResolver  
 */
@Configuration
public class Global03Exception implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 
        ModelAndView mv = new ModelAndView();
        //   
        if (e instanceof ArithmeticException){
            mv.setViewName("error1");
        }
        if (e instanceof NullPointerException){
            mv.setViewName("error2");
        }
        mv.addObject("error",e.getMessage());
        return mv;
    }
}
  
예에서thymeleaf 템플릿을 사용하여 다음과 같이 설정했습니다.#  
spring.thymeleaf.cache=true
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
                
                    
        
    
    
    
    
    
                
                
                
                
                
                
                    
                        
                            
                            
                                
                                    
                                    이 내용에 흥미가 있습니까?
                                
                            
                            
                            
                            현재 기사가 여러분의 문제를 해결하지 못하는 경우  AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
                            
                                
                                Pytest 테스트 프레임워크 기본 사용 방법 상세 정보
                            
                            pytest 소개
2. 매개 변수화를 지원하여 테스트할 테스트 용례를 세밀하게 제어할 수 있다.
3. 간단한 단원 테스트와 복잡한 기능 테스트를 지원할 수 있고selenium/appnium 등 자동화 테스트, 인터페...
                            
                            
                            
                            
                            텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
                            
                        
                    
                
                
                
            
    
 
 
@Controller
public class Demo01Controller {
    @RequestMapping("/demo01")
    public String showInfo1(){
        String str = null;
        //      
        str.length();
        return "index";
    }
    @RequestMapping("/demo02")
    public String showInfo2(){
        int a = 10 / 0 ;
        return "index";
    }
    /**
     *   java.lang.ArithmeticException
     *   ModelAndView: 
     *  
     * @param  e   Exception e: 
     * @return
     */
    @ExceptionHandler(value = {java.lang.ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
    /**
     *   NullPointException  
     * @param e
     * @return
     */
   @ExceptionHandler(value = {NullPointerException.class})
    public ModelAndView nullpointException(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error",e.toString());
        mv.setViewName("error2");
        return mv;
    }
    
     -ArithmeticException  
    ArithmeticException
   
    
     -NullPointerException   
     NullPointerException
   
/**
 *       @ControllerAdvice
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class Global01Exception {
    /**
     *  
     * @param e
     * @return
     */
    @ExceptionHandler(value = {java.lang.NullPointerException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
}
/**
 * @desc    SimpleMappingExceptionResolver  
 */
@Configuration  
public class Global02Exception {
    /**
     *      SimpleMappingExceptionResolver
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        /**
         *  1     
         *  2  
         */
        mappings.put("java.lang.NullPointerException", "error1");
        mappings.put("java.lang.ArithmeticException", "error2");
        // 
        resolver.setExceptionMappings(mappings);
        return resolver;
    }
}
/**
 * @desc    HandlerExceptionResolver  
 */
@Configuration
public class Global03Exception implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 
        ModelAndView mv = new ModelAndView();
        //   
        if (e instanceof ArithmeticException){
            mv.setViewName("error1");
        }
        if (e instanceof NullPointerException){
            mv.setViewName("error2");
        }
        mv.addObject("error",e.getMessage());
        return mv;
    }
}
#  
spring.thymeleaf.cache=true
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Pytest 테스트 프레임워크 기본 사용 방법 상세 정보pytest 소개 2. 매개 변수화를 지원하여 테스트할 테스트 용례를 세밀하게 제어할 수 있다. 3. 간단한 단원 테스트와 복잡한 기능 테스트를 지원할 수 있고selenium/appnium 등 자동화 테스트, 인터페...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.