gpt4 book ai didi

Spring-Boot - 错误处理

转载 作者:行者123 更新时间:2023-12-02 06:37:04 26 4
gpt4 key购买 nike

我正在尝试在 Spring-Boot 中为我的 Controller 编写错误处理程序,以捕获大多数可能的错误(Spring、sql 等)。到目前为止,我能够获得带有 Nulls 的 JSON 响应,但是我无法在其中放入任何数据。当我尝试获取错误消息时,我只收到一个空白页。

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

@RestController
public class BasicErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";

@RequestMapping(value=ERROR_PATH)
@ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {
ErrorBody eBody = new ErrorBody();
eBody.setMessage(e.getCause().getMessage());
return eBody;
}
}
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ErrorBody {
private String dateTime;
private String exception;
private String url;
private String message;
}

最佳答案

你可以这样做:

 @ControllerAdvice
public class ControllerExceptionTranslator {


@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
SimpleErrorMessage handleException(EntityNotFoundException exception){
log.debug("Entity Not Found Exception {}",exception.getMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Entity not found","This resource was not found");
}


@ExceptionHandler({UsernameNotFoundException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
SimpleErrorMessage handleException(UsernameNotFoundException exception){
log.debug("Username not found {}",exception.getLocalizedMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Unaouthorized"," ");
}


}

关于Spring-Boot - 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28501154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com