在我的应用程序中,我想处理AccessDeniedException
并返回Json内容以作出回应。有人可以解释如何做到这一点?我找不到答案。我尝试使用@ExceptionHandler
捕获异常但我总是重定向到登录页面。我正在写api所以我不需要整个mvc。
有什么想法吗?
答案 0 :(得分:0)
您可以引入能够将AccessDeniedException
转换为JSON响应的HandlerExceptionResolver:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Component("handlerExceptionResolver")
public class RestExceptionResolver implements HandlerExceptionResolver {
private final ObjectMapper objectMapper;
@Autowired
public RestExceptionResolver(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
if (exception instanceof AccessDeniedException) {
try {
//you can use a pojo instead of a map too
Map<String, Object> data = new HashMap<String, Object>();
data.put("status", HttpServletResponse.SC_FORBIDDEN);
data.put("message", "my custom message");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(response.getOutputStream(), data);
//exception handled
return new ModelAndView();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
//default processing
return null;
}
}