统一异常的处理方法

一:知识点:

1.@RestControllerAdvice

  1. 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。
  2. 注解了@RestControllerAdvice的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。
  3. @RestControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上。
  4. @ExceptionHandler:用于指定异常处理方法。当与@RestControllerAdvice配合使用时,用于全局处理控制器里的异常。
  5. @InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
  6. @ModelAttribute:本来作用是绑定键值对到Model中,当与@ControllerAdvice配合使用时,可以让全局的@RequestMapping都能获得在此处设置的键值对

二,异常代码展示

package com.example.demo_webmvc.zeng.exception;

import com.example.demo_webmvc.zeng.util.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义异常消息
 */
@RestControllerAdvice
public class ZengException {
    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R  runimeError(Exception e){
        System.out.println("运行异常---"+e.getMessage());
        System.out.println("全局异常--执行");
        return R.error("全局异常--执行");
    }
    /**
     * 特定异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    public R  runime2Error(RuntimeException e){
        System.out.println("运行异常---"+e.getMessage());
        System.out.println("特定异常--执行");
        return R.error("特定异常--执行");
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public R  runime1Error(CustomException e){
        System.out.println("运行异常---"+e.getMessage());
        System.out.println("自定义异常--执行");
        return R.error("自定义异常--执行");
    }
}
package com.example.demo_webmvc.zeng.exception;

/**
 * 异常方法
 */
public class CustomException extends Exception {
    /**
     * 自定义异常
     * @param message
     */
    public CustomException(Exception message) {
        super(message);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_55699184/article/details/132791474