Record springboot exception handling and custom exceptions

Global exception handling

package com.van.mall.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Van
 * @date 2020/3/24 - 10:49
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandler {
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ServerResponse handler(Exception e){
      log.error("system error",e);
        return    ServerResponse.error("zero can divide");
    }
}

Explanation:

@ControllerAdvice to identify it is a global exception handling class
@ExceptionHandler identify which exception class to capture it, here is the Exception, as long as the description is abnormal, all capture (since all exceptions are inherited Exception)
@ResponseBody identity, I What you want to return is json instead of view.
In the method, you need to add the Exception e parameter, because an exception will be passed in this method in this method.

Custom exception

package com.van.mall.common;

import lombok.Data;

/**
 * @author Van
 * @date 2020/3/24 - 10:55
 */
@Data
public class ZeroException extends RuntimeException {
    private String message;
    private int code;

    public ZeroException(String message, int code) {
        super(message);
        this.code = code;
    }
}

Explanation:

The custom exception directly inherits RuntimeException, it only needs two members, message and code, and to get set, and a constructor (where the constructor super directly calls the constructor of the parent class to assign a value to the message)
when used Direct throw new ZeroException ("0 cannot be used as a divisor", -1)

Published 56 original articles · Like1 · Visits1509

Guess you like

Origin blog.csdn.net/weixin_44841849/article/details/105067070