1.公共异常
package com.example.demo.exception;
import com.example.demo.response.Response;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(Exception.class)
public Response<String> handleException(Exception e) {
return Response.error(e.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Response<String> handleBusinessException(BusinessException e) {
return Response.error(e.getCode(),e.getMessage());
}
}2.自定义异常
package com.example.demo.exception;
import lombok.Data;
@Data
public class BusinessException extends RuntimeException{
private String message;
private int code;
public BusinessException(String message, int code) {
this.message = message;
this.code = code;
}
public BusinessException(String message) {
this.message = message;
this.code = 500;
}
}本文为看恩吧原创文章,转载无需和我联系,但请注明来自knsay.com